Dennis Castelijns Dennis Castelijns - 2 months ago 18
CSS Question

Some problems with a jQuery animation

I am working for the first time with jQuery and I'm trying to make an animation on a div. The first animation goes well but the second one (when I want to return the div to its original position it just resets. I cant figure it out.

My jQuery:

$(document).ready(function() {


// Row one - column one.
$(document).on('click', '#row_one_column_one', function() {

$('#row_one_column_one').animate({
left: '35%',
opacity: '0.9',
height: '500px',
width: '500px'
});

$('#row_one_column_one_button').fadeIn(750);
});

$(document).on('click', '#row_one_column_one_button', function() {
$('#row_one_column_one_button').fadeOut(250);
$('#row_one_column_one').animate({
left: '100px',
opacity: '0.5',
height: '250px;'
});
});


});


I also made a fiddle: https://jsfiddle.net/c1he2vb8/4/

Please spare me I'm still a noob.

KAD KAD
Answer

This is because of event delgation (bubbling), the parent div click is triggering and re-executing the animation event, that why it is resetting.

In order to fix this problem you need to add e.stopPropagation() to the click button that shall stop the delegation and execute only the click method of the "click me" button:

$(document).on('click', '#row_one_column_one_button', function(e) {
        e.stopPropagation();
        $('#row_one_column_one_button').fadeOut(250);
        $('#row_one_column_one').animate({
            left: '100px',
            opacity: '0.5',
            height: '250px;'
        });
    });

Check the documentation for event propagation : https://developer.mozilla.org/en/DOM/event.stopPropagation