scroll to top of page on button click javascript code example

Example 1: javascript go to top of page

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

Example 2: javascript scroll to top onclick

//EITHER:

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

//OR:

window.scroll({top: 0, left: 0});
//Or with jQuery
$('html,body').scrollTop(0);
//with animation
$('html, body').animate({ scrollTop: 0 }, 'fast');

Example 3: scroll to top

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

Example 4: simple button scrolling with this

// Select all »a« elements with a parent tag »nav« and add a function that is executed on click
$('#id a').on('click', function (e) {

   // Define variable of the clicked »a« element (»this«) and get its href value.
   var href = $(this).attr('href')

   // Run a scroll animation to the position of the element which has the same id like the href value.
   $('html, body').animate({
      scrollTop: $(href).offset().top
   }, '300')

   // Prevent the browser from showing the attribute name of the clicked link in the address bar
   e.preventDefault()

})

Example 5: javascript scroll to top onclick

window.scroll({top: 0, left: 0});
//Or with jQuery
$('html,body').scrollTop(0);
//with animation
$('html, body').animate({ scrollTop: 0 }, 'fast');