scroll up javascript code example

Example 1: javascript scroll to top of page

//Instant scroll to top of page
window.scrollTo(0, 0);

Example 2: javascript go to top of page

window.scroll({
 top: 0, 
 left: 0, 
 behavior: 'smooth' 
});

Example 3: scroll down up js

var lastScrollTop = 0;

// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
element.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
   var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
   if (st > lastScrollTop){
      // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);

Example 4: scroll to top

$("#scroll_icon").click(function()
	{
		jQuery('html,body').animate({scrollTop:0},2000);
	})

Tags:

Html Example