In any case (jQuery or vanilla JavaScript) you want to do the following:
- Select all anchor tags where
href set to #top - Create a jump function that sets the top position of the page and returns
false to prevent the default link behavior - Bind the transition function to the
click event of all found nodes
To go, you have several options. I provided them (jQuery and JS specifics) in the first example below.
Using jQuery
jQuery makes selecting and binding to the click event easier. You can then go to the top of the page using jQuery or direct JavaScript.
$('a[href="#top"]').click(function() { // // To jump, pick one... // // Vanilla JS Jump window.scroll(0,0) // Another Vanilla JS Jump window.scrollTo(0,0) // jQuery Jump $('html,body').scrollTop(0); // Fancy jQuery Animated Scrolling $('html,body').animate({ scrollTop: 0 }, 'slow'); // // ...then prevent the default behavior by returning false. // return false; });
jQuery animate provides options for animation duration and easing along with the ability to set a callback.
Vanilla javascript
You can also use Vanilla JS all the way ... Queries and bindings, however, become a bit more painful.
Modern browsers support document.querySelectorAll() , which allows you to capture all link elements in the same way as with jQuery:
var links = document.querySelectorAll('a[href="#top"]');
Then iterate over the elements and attach the "jump":
for (var i = links.length - 1; i >= 0; i--) { links[i].onclick = function() { window.scroll(); return false; }; };
If your target browser does not give you querySelectorAll , you simply look at all the anchor tags to find those related to #top :
var links = document.body.getElementsByTagName('a'); for (var i = links.length - 1; i >= 0; i--) { var l = links[i]; if(l.getAttribute('href') === '#top') { l.onclick = function() { window.scroll(); return false; } } }