How to Create a Switch Button Using jQuery?

Estimated read time 2 min read

To create a switch button using jQuery, you can use the prop() method to change the value of the checked attribute of a checkbox input element. Here’s an example code snippet:

HTML:

<label class="switch">
  <input type="checkbox" id="switch-button">
  <span class="slider"></span>
</label>

CSS:

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  display: none;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

jQuery:

$(document).ready(function() {
  $('#switch-button').click(function() {
    if ($(this).prop('checked')) {
      // switch is on
      // add code to be executed when the switch is turned on
    } else {
      // switch is off
      // add code to be executed when the switch is turned off
    }
  });
});

Explanation:

  1. The HTML code defines a label element with the class switch that contains an input element with the type="checkbox" and id="switch-button" attributes and a span element with the class slider.
  2. The CSS code styles the switch button with a slider and a circle that moves to the right when the switch is turned on.
  3. The $(document).ready() function ensures that the jQuery code is executed only after the page has finished loading.
  4. The $('#switch-button').click() function specifies that when the checkbox input element with the ID switch-button is clicked, the following code is executed.
  5. The $(this).prop('checked') method returns the value of the checked attribute of the checkbox input element.
  6. If the value of the checked attribute is true, the code block for when the switch is turned on is executed. If the value of the checked attribute is false, the code block for when the switch is turned off is executed.

When the user clicks the switch button, the value of the checked attribute of the checkbox input element is changed and the corresponding code block is executed. You can customize the switch button by modifying the HTML, CSS, and jQuery code.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply