javascript - Remove/avoid adding target link to URL -
this 1 may simple jquery/javascript gurus here, can't find solution around web.
case
i have link @ bottom of page says back top, link target link this:
<a href="#top" class="standard">back top</a> so when click it, jumps top of page. simple.
problem
when target link clicked, id #top added url of page, ie:
http://website.com/about-us/#top question
is there way remove or avoid getting id #top added url of page retain functionality of page jumping top?
any appreciated.
in either case (jquery or vanilla javascript), you'll want following:
- select anchor tags
hrefset#top - create "jump" function sets page position top , returns
falseprevent default link behavior - bind "jump" function
clickevent of of nodes found
to jump have several options. i've provided them (jquery , js specific) in first example below.
using jquery
jquery makes selecting , binding click event easy. can jump top of page using jquery or straight javascript.
$('a[href="#top"]').click(function() { // // jump, pick one... // // vanilla js jump window.scroll(0,0) // 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 default behavior returning false. // return false; }); jquery's animate provides options animation duration , easing along ability set callback.
vanilla javascript
you can use vanilla js whole way through... querying , binding, however, become bit more painful.
modern browsers support document.queryselectorall() allow grab of link elements jquery:
var links = document.queryselectorall('a[href="#top"]'); then loop on elements , bind "jump":
for (var = links.length - 1; >= 0; i--) { links[i].onclick = function() { window.scroll(); return false; }; }; if target browser doesn't gift queryselectorall loop through of anchor tags find ones linked #top:
var links = document.body.getelementsbytagname('a'); (var = links.length - 1; >= 0; i--) { var l = links[i]; if(l.getattribute('href') === '#top') { l.onclick = function() { window.scroll(); return false; } } }
Comments
Post a Comment