Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; 
 });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading