In some projects that I work on, I need a quick way of adding some cool-looking user-friendly on/off switch. Checkboxes are ugly! And I don’t want to add a new component/plugin to the already loaded pages. So, I wrote some quick code snippet for a switch based on Bootstrap 3 and jQuery. Here is the HTML code:
1 2 3 4 |
<div class="btn-group" id="toggle_event_editing"> <button type="button" class="btn btn-info locked_active">OFF</button> <button type="button" class="btn btn-default unlocked_inactive">ON</button> </div> |
And here is the jQuery code (should be placed inside any jQuery DOM loaded block):
1 2 3 4 5 6 7 8 9 10 11 |
$('#toggle_event_editing button').click(function(){ if($(this).hasClass('locked_active') || $(this).hasClass('unlocked_inactive')){ /* code to do when unlocking */ }else{ /* code to do when locking */ } /* reverse locking status */ $('#toggle_event_editing button').eq(0).toggleClass('locked_inactive locked_active btn-default btn-info'); $('#toggle_event_editing button').eq(1).toggleClass('unlocked_inactive unlocked_active btn-info btn-default'); }); |
Here is what the output looks like when the page loads (the default state is locked):
And when the switch is clicked, here is how it looks like (unlocked):
Here is a demo of the switch in action. Have fun!