David. E David. E -5 years ago 126
jQuery Question

jQuery animation on divs that share the same class name

I'd like to know if it's possible to animate certain divs that share the same class. Once a div is clicked, the animation has to happen only within the clicked div and not on all other divs at the same time.

Here's my code so far:

$(".js-wrapper-item").click(function () {
var box = $(this);

if ($('.js-wrapper-item').is(':animated')) {

if ($(box).css('bottom') == '0px') {
$(box).stop().animate({ "bottom": "50px"}, 600);

else {
$(box).animate({"bottom": "0px"}, 600);

So far, I've been able to make this code working properly only by having divs that have different names. Can you guys give me some pointers on how to achieve what I'm looking for? Thanks a lot!

Answer Source

Use event delegation like below:


instead of $(".js-wrapper-item").click(function (){.

Also, you can use $(this).is(':animated')){ when you write that block within the click event. you do not need to refer the element as $('.js-wrapper-item').is(':animated')) again.

You also don't need var box = $(this). You can directly call $(this) instead of $(box) when it is within the same click block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download