All radio button styles in jQuery beautify project

CSS style

 .custom-radio {
 	float: left;
 }
 .custom-radio input {
     position: absolute;
     left: -9999px;
     vertical-align: middle;
 }
 .custom-radio label {
     cursor: pointer;
     padding-right: 20px;
     line-height: 30px;
     padding-left: 25px;
     position: relative;
     display: inline-block;
 }
 .custom-radio label:hover {
 	color: #FF6200;
 }
 .custom-radio label::after {
     content: '';
     display: block;
     position: absolute;
     top: 6px;
     left: 0;
     width: 16px;
     height: 16px;
     outline: 0;
     border: 1px solid #D5D5D5;
     border-radius: 50%;
 }
 .custom-radio label.checked::after {
     border: 6px solid #FF6200;
     width: 6px;
     height: 6px;
 }
 .custom-radio label,
 .custom-radio label.checked {
     border: none;
     background: none;
 }

HTML

 <input type="radio" name="yesOrNo" id="yes" checked />
 <label for="yes">Yes</label>
 <input type="radio" name="yesOrNo" id="no" />
 <label for="no">No</label>

Realization ideas

  1. Define a JQuery extension method. After the page is loaded, the input radio is called cyclically.
  2. Create a new Div and set the class name to define css.
  3. Use the input ID to get the relevant label, put the input radio and the label of the corresponding id into the above Div.
  4. Bind custom events, trigger it, bind click, focus and other events.
<script src="./jquery-1.11.1.min.js"></script>
<script>
  $.fn.customInput = function () {
    return $(this).each(function () {
      if ($(this).is('[type=radio]')) {
        var input = $(this);

        var label = $('label[for=' + input.attr('id') + ']');
        label.add(input).wrapAll('<div class="custom-' + input.attr('type') + '"></div>');
        label.hover = function () {
          $(this).addClass('hover');
        };
        input.bind('updateState', function () {
            input.is(':checked') ? label.addClass('checked') : label.removeClass('checked');
          })
          .click(function () {
            $('input[name=' + $(this).attr('name') + ']').trigger('updateState');
          })
          .focus(function () {
            // Custom processing logic
            label.addClass('focus');
            if (input.is(':checked')) $(this).addClass('checkedFocus');
          })
          .blur(function () {
            // Custom processing logic
            label.removeClass('focus checkedFocus');
          });
      }
    });
  };
  $('input:radio').each(function () {
    var $this = $(this);
    $this.customInput(); // Initialize radio buttons
  });
</script>

Leave a Reply