10

Since the jQuery .toggle event method is deprecated. What are we suppose to use to simulate this event (alternate clicks)?

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697

2 Answers2

9

Add this outside of document.ready

$.fn.clicktoggle = function(a, b) {
    return this.each(function() {
        var clicked = false;
        $(this).click(function() {
            if (clicked) {
                clicked = false;
                return b.apply(this, arguments);
            }
            clicked = true;
            return a.apply(this, arguments);
        });
    });
};

then use the following to replicate the .toggle functionality:

$("#mydiv").clicktoggle(functionA,functionB);

Found on the JQuery Forums

Jay Lane
  • 1,379
  • 15
  • 28
  • Sorry, but what exactly is this? Is it a function you wrote? Why $.fn.clicktoggle and how do you call this function? Thank you for your anwser! –  Jul 11 '13 at 00:41
  • The above code extends the jQuery object by adding a new method. You would add that code to your "_on ready_" handler. Then you can invoke `clicktoggle()` as if it was a jQuery method. You can read about adding a jQuery method [here](http://stackoverflow.com/q/12093192/778118). – jahroy Jul 11 '13 at 00:44
  • no problem, if it worked for you if you can add it as solved that would be great – Jay Lane Jul 11 '13 at 00:47
  • 1
    Yes, I have to wait 4 minutes :). –  Jul 11 '13 at 00:48
-1
var i = 0;    
$('button').click(function() { 
    if (i == 0){        
        $('div').css({background: 'red'}) 
        i++; 
    } else { 
        $('div').css({background: 'yellow'}) 
        i = 0; 
    }
});
Quinn Comendant
  • 9,686
  • 2
  • 32
  • 35
Pomme Zede
  • 11
  • 1