Search code examples
jquerysettimeoutscrolltop

setTimeout and scrollTop animation on click not working in accordion


I would the active/expanded accordion item to jump to the top when clicked. This position changes as the accordions have not finished sliding open or closed resulting in an offset.

I have learned that I need to wrap this function in setTimeout so it executes after the sliding animation is complete. Here is my code so far

$('.accordion-title').on('click', function() {
var content = $(this).next();

$('.accordion-content').not(content).slideUp(400);
$('.accordion-title').not(this).removeClass('expanded');
$(this).toggleClass('expanded');
content.slideToggle(400);
        
$('html,body').animate({scrollTop: $(this).offset().top}, 100);

});

I have tried the below but it results in an error

setTimeout(function(){
$('html,body').animate({scrollTop: $(this).offset().top}, 100);
},400);

Here is my fiddle


Solution

  • do you need the this code ?

    $('.accordion-title').on('click', function() {
        var content = $(this).next();
    
        $('.accordion-content').not(content).slideUp(400);
        $('.accordion-title').not(this).removeClass('expanded');
        $(this).toggleClass('expanded');
        
        var self = this;
        content.slideToggle(400, function(e) {
            $('html,body').animate({scrollTop: $(self).offset().top}, 100); 
        });
        
       
    
    });