Reversing jquery effect

3

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

$(document).ready(function(){           
    $('html').click(function(){             
        $('.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" ??

    
asked by anonymous 04.04.2015 / 05:06

1 answer

2

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() { 
  $(this).toggleClass("outraClasse");
});

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];
    this.data('toggleclicked', 0);
    this.click(function() {
        var data = $(this).data();
        var tc = data.toggleclicked;
        $.proxy(funcs[tc], this)();
        data.toggleclicked = (tc + 1) % 2;
    });
    return this;
};
}(jQuery));

So your code looks like this:

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

Fiddle: link

Reference

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

    
04.04.2015 / 05:44