Reversing the jquery effect

Asked

Viewed 53 times

3

I am 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 any of the html is performed the effect runs!

Only that type, if I click once the effect runs! How to do so so that I click again the effect if "revert"??

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 alternating the object class. Imagine a blue div, and you want it to turn yellow. Make it blue and then create a class to make it yellow. So by clicking anywhere, jQuery adds the new class to the object, and when you click again, it removes. Example:

$("#bloco").click(function() { 
  $(this).toggleClass("outraClasse");
});

Fiddle: http://jsfiddle.net/1ktu8xob/

Remembering that it is important to place the property transition in the element, so you can control the time 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 would look 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: http://jsfiddle.net/shw51knq/


Reference

Code for the 2nd method taken from that answer: https://stackoverflow.com/a/4911660/3126013

  • ! I know it’s not the focus of the site, but could you point me somewhere to learn more about jquery?

  • 2

    Look, I’ll be honest with you, I think following a guide doesn’t get you anywhere, because you don’t apply what you learn (actually, it depends a lot on you). I recommend you to study Javascript first, so you can go to a framework (like jQuery). I think it’s really cool (and it’s how I study most programming languages) that you invent a project and apply all your knowledge to it. When you come across something you don’t know how to do, google it! The jQuery documentation is great, if you are in any doubt take a look at it: https://api.jquery.com/ Good studies!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.