javascriptjqueryjquery-animatetogglescrolltop

Scroll to the top of the page and back to previous position onclick using Jquery


$('.course-header').click(function() { $("html, body").animate({scrollTop: 0}, "smooth"); return false; });

The page will scroll to the top of the page when ".course-header" clicked but I also want the page to scroll back to the previous (original) position when ".course-header" is clicked again. What can I do to make it happen?

I have tried to combining ".toggle()" with ".animate()" but it didn't work.


Solution

  • One solution is to declare a variable for tracking the scroll position and use it to return to the previous position on click:

    //declare variable to track scroll position
    let yscrollpos = 0;
    
    $('.course-header').click(function() {
        if(yscrollpos > 0) {
           $("html, body").animate({
              scrollTop: yscrollpos
           }, "smooth");
           yscrollpos = 0;
        } else {
           //get current scroll position
           yscrollpos = $(document).scrollTop();
           $("html, body").animate({
              scrollTop: 0
           }, "smooth");
        }
         
        return false; 
     });