Tag Archives: jquery

Creating an ON/OFF switch using bootstrap and jQuery

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:

And here is the jQuery code (should be placed inside any jQuery DOM loaded block):

Here is what the output looks like when the page loads (the default state is locked): jquery-bootstrap-locked-switch

And when the switch is clicked, here is how it looks like (unlocked): jquery-bootstrap-unlocked-switch

Here is a demo of the switch in action. Have fun!

Moving from Prototype to jQuery

AppGini used to use Prototype and Scriptaculous javascript framework for client-side scripting. It’s a great framework but it’s not being frequently updated any more, and finding plugins for it is getting harder. So, I decided to move on and migrate to jQuery. jQuery is in very active development, has a huge user base, has a huge library of actively-developed plugins, and is used by many great client-side frameworks, like bootstrap for example.

During the migration, I created a checklist of code lines I needed to change. I thought this would be useful for anyone who wishes to follow this path. Feel free to add your own points in the comments.

Prototype code To convert to jQuery, replace with
document.observe("dom:loaded", function(){ some_code }); jQuery(function(){ some_code });
$$(selector)[x] jQuery(selector).eq(x)
$('id') jQuery('#id')
.style.x = 'y' .css({ x: 'y' })
.checked .prop('checked')
.disabled .prop('disabled')
.some_attr .attr('some_attr')
.value = x .val(x)
.observe('event', function(){}) .event(function(){})
$F('id') $('#id').val()
.fade({duration: x}) .fadeOut(x * 1000)
.appear({duration: x}) .fadeIn(x * 1000)
Effect.Appear fadeIn()
Effect.Fade fadeOut()
.update('new content') .html('new content')

Tip: To work directly with DOM methods after selecting an element through a jQuery selector, use get(0) or [0] .. for example:

// or