The humble learner
The humble learner

Reputation: 23

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.

Upvotes: 2

Views: 909

Answers (1)

Ryan Wilson
Ryan Wilson

Reputation: 10765

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; 
 });

Upvotes: 1

Related Questions