Delegate / bind toggle event jquery

11 years ago, July 9, 2013
Reading time: 1 mins

The toggle event cannot be delegated using jquery but we can do similar using the click event and some flags.

 


var counter = 0;
jQuery('body').delegate('#toggle-button','click',function(e){
     e.preventDefault();
     if(++counter%2){
        alert('on');
     }else{
         alert('off');
     }
  });     

The code is self explanatory. The counter is incremented on each click event and checked if it is even or odd, according to it alternately On or Off is alerted.

Previous
CSS to resize / crop / center background image
Next
Scroll Horizontally on mouse wheel scroll – Example: Horizontal scroller showcase
© 2024 Anil Maharjan