Remove/avoid adding target link to URL

Ricardo Zea

This one may be simple for the jQuery/JavaScript gurus here, but I just can't find a solution for it around the web.

Case

I have a link at the bottom of a page that says Back to Top, the link is simply a target link like this:

<a href="#top" class="standard">Back to Top</a>

So when you click it, it jumps to the top of page. Simple.

Problem

When the target link is clicked, the id #top is added to the URL of the page, ie:

http://website.com/about-us/#top

Question

Is there a way to remove or avoid getting that id #top added to the URL of the page but retain the functionality of the page jumping to the top?

Any help with this is greatly appreciated.

fny

In either case (jQuery or vanilla JavaScript), you'll want to do the following:

  • Select all anchor tags where href is set to #top
  • Create a "jump" function which sets the page position to the top and returns false to prevent the default link behavior
  • Bind the "jump" function to the click event of all of the nodes found

To jump you have several options. I've provided them (jQuery and JS specific) in the first example below.

Using jQuery

jQuery makes selecting and binding to a click event easy. Then you can jump to the top of the page using jQuery or straight 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's animate provides options for animation duration and easing along with the ability to set a callback.

Vanilla JavaScript

You can also use Vanilla JS the whole way through... Querying and binding, however, become a bit more painful.

Modern browsers support document.querySelectorAll() which will allow you to grab all of the link elements just as you would with jQuery:

var links = document.querySelectorAll('a[href="#top"]');

Then loop over the elements and bind the "jump":

for (var i = links.length - 1; i >= 0; i--) {
  links[i].onclick = function() { window.scroll(); return false; };
};

If your target browser doesn't gift you with querySelectorAll you just loop through all of the anchor tags to find the ones linked 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; }
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related