Reversing jquery effect

Posted on

Question :

I’m learning Jquery. And I made the following code

        $('.box').css("background-color", "#666");
        $('.box').animate({"width":"400px"}, 1000);             

In this code when clicking on any of the html is performed the effect goes into effect!

Just like, if I click once the effect executes! How do I then re-click the effect if it “reverts” ??


Answer :

You have two ways of doing what you want:

1st method

There is a command in jQuery called toggleClass , you can use it to get what you want by switching the object class. Imagine a blue div, and you want it to turn yellow. Make it blue and then create a class for it to turn yellow. So by clicking anywhere, jQuery adds the new class to the object, and when it clicks again, it retreats. Example:

$("#bloco").click(function() { 

Fiddle: link

Remembering that it’s important to put the transition property on the element, so you can control the tempo of the transition animations.

2nd method

You can use this JavaScript code to create a variation function between clicks:

(function($) {
$.fn.clickToggle = function(func1, func2) {
    var funcs = [func1, func2];'toggleclicked', 0); {
        var data = $(this).data();
        var tc = data.toggleclicked;
        $.proxy(funcs[tc], this)();
        data.toggleclicked = (tc + 1) % 2;
    return this;

So your code looks like this:

    $(this).css("background-color", "#666");
    $(this).animate({"width":"400px"}, 1000);             
}, function() {
    $(this).css("background-color", "blue");
    $(this).animate({"width":"50px"}, 1000);    

Fiddle: link


Code for the 2nd method I get from this answer: link


Leave a Reply

Your email address will not be published. Required fields are marked *