javascript - Prevent hash change from scrolling -
sorry ugly layout example below... http://www.wthdesign.net/test/test2.html
i managed append id name url:
function generateurl(el) { var currentid = $(el).attr('id'); document.location.hash = currentid; }
and add:
<a id="abc2" onclick="generateurl(this)" >this anchor btn</a>
but end having same effect as:
<a id="abc2" href="#abc2" >this anchor btn</a>
everything fine don't want scroll when when click on link how should that? many in advance.
if ids aren't necessary, href="#some-value
change window location without scrolling page. if need id
in document (on tags in case) location change cause scroll. can work around using history
object in modern browsers or storing scroll location on link click, resetting using hashchange
event.
i use markup both solutions:
sample markup:
<div class="filler"></div> <a id="abc1" href="#abc1" class="my-class">this anchor btn</a> <div class="filler"></div> <a id="abc2" href="#abc2" class="my-class">this anchor btn</a> <div class="filler"></div> <a id="abc3" href="#abc3" class="my-class">this anchor btn</a> <div class="filler"></div>
history.replacestate or history.pushstate
//get element referneces var elems = document.getelementsbyclassname('my-class'); //iterate on references (var i=0; i<elems.length; ++i) { //add click function each element elems[i].addeventlistener('click', clickfunc); } //this store scroll position var keepscroll = false; //fires when ".my-class" link clicked function clickfunc(e) { //prevent default behavior of link e.preventdefault(); //add hash history.replacestate({}, '', e.target.href); }
scrolltop , hashchange event
javascript:
//get element referneces var elems = document.getelementsbyclassname('my-class'); //iterate on references (var i=0; i<elems.length; ++i) { //add click function each element elems[i].addeventlistener('click', clickfunc); } //this store scroll position var keepscroll = false; //fires when ".my-class" link clicked function clickfunc(e) { //if location hash set link if (window.location.hash === '#'+e.target.id) { //do nothing e.preventdefault(); } else { //the location change - store scroll position keepscroll = document.body.scrolltop; } } window.addeventlistener('hashchange', function(e) { //the location has has changed //if "keepscroll has been set if (keepscroll !== false) { //move scroll position stored position document.body.scrolltop = keepscroll; //set "keepscroll" false behavior won't affect irrelevant links keepscroll = false; } });
Comments
Post a Comment