简体   繁体   中英

jQuery - Run function after CSS transition is done

I have an accordion with CSS animation that expands the clicked li. This is done using li:target.

Now, I want to scroll to the id that is clicked, but because of the css transition, it ends up being positioned where the li was before the transition was activated.

This is my javascript snippet as of now:

$(document).on('click', '#accordion li', function (e){
    e.preventDefault(); 

      // Call the scroll function
    goToByScroll($(this).attr("id"));
    $('#accordion li').height('');
    $(this).height($('section', $(this)).outerHeight() + $('a', $(this)).outerHeight());
});

// This is a functions that scrolls to #ID

function goToByScroll(id){
    // Scroll
    // Wait until CSS transition is done

    $("#"+id).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ 
        $('html,body').animate({
            scrollTop: $("#"+id).offset().top},
            'fast');
        $("#"+id).unbind();
    });  
}   

Edit2: After Piotr's suggestion, unbinding the event fixed the buggy behaviour I was having :)

You can try:

$("#"+id).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(event){ 
    $('html,body').animate({
    scrollTop: $("#"+id).offset().top},
    'fast'
    );
    $(this).unbind(event);
});

Edit: Added the unbind instruction.

it's hard to know when the transition ends. You could asume 1000ms eg.

window.setTimeout(function () {
   // your scrolling
}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM