Skip to content

Instantly share code, notes, and snippets.

@mrosata
Created August 2, 2015 18:47
Show Gist options
  • Select an option

  • Save mrosata/958cc93080f1a4e6faa6 to your computer and use it in GitHub Desktop.

Select an option

Save mrosata/958cc93080f1a4e6faa6 to your computer and use it in GitHub Desktop.
/**
* This was a refactor to a loop that was building events on a series of toggle switches.
* The nature of the events binding would break upon ajax page loading (if it overwrote bs-toggles).
* To make it dynamic I had to refactor original code (top) to the nice code (bottom) which is
* independant of toggle switches themselves. It listens on a anscestor container. An element which
* will never be overwritten by ajax. On some pages this would have to be <body> perhaps.
*/
// Original Code. Author unknown.
$('.switch-toggle').each(function(i,ob){
$(ob).click(function(){
var ckd = $('input',ob).is(':checked');
$('input',ob).prop('checked',!ckd).closest(ob).toggleClass('swith-on',!ckd);
}).toggleClass('swith-on',$('input',ob).is(':checked'));
});
// Ajax Safe Refactor .Author me.
$('#someModule1').on('click.module1', '.switch-toggle', function(e) {
var checkbox = $(this).find('input'),
checked = checkbox.is(':checked');
checkbox.prop('checked', !checked).parent('.switch-toggle').toggleClass('swith-on', !checked);
// Return false - to bubble may trigger double clicking (which would give appearance of no response)
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment