Search code examples
javascriptjquerycsscss-transitionstoggleclass

Using JQuery toggleclass to manipulate click transitions


I am trying to make a nice transition when clicking a button. The button is basically a div which triggers a Jquery function. The button consists of some text and a FontAwesome icon.

I want to use JQuery in a way that when I click on the button, the FA icon rapidly changes in size and back, so people get some kind of animated confirmation of clicking the button. I created a class with a transition which increases the font-size at least:

#keepbtn.clicked {
    font-size:3em;
    opacity:0.8;
    -webkit-transition: all 0.1s ease 0s;
    -moz-transition: all 0.1s ease 0s;
    -ms-transition: all 0.1s ease 0s;
    -o-transition: all 0.1s ease 0s;
    transition: all 0.1s ease 0s;   
}

And I tried toggling between classes using a delay:

$("#keepbtn").toggleClass("clicked").delay(250).toggleClass("clicked");

But this does not work; it does not change anything. However, this works (but does not change it back to original size of course:

$("#keepbtn").toggleClass("clicked");

Any ideas? I'm rather new to transitions and JQuery so I might be adopting the wrong approach altogether.

Thanks in advance.


Solution

  • In order for delay() to work on non-animated elements, you have to "queue" operators :

    $("#keepbtn")
        .toggleClass("clicked")
        .delay(250)
        .queue(function(nxt) {
             $(this).toggleClass("clicked");
             nxt();
        });