jquery - javascript: Avoid browser scrolling back to top on content insertion -
jquery - javascript: Avoid browser scrolling back to top on content insertion -
i thought easy solve, can`t seem find solution anywhere. it's annoying javascript 'feature?'. every time add together content div document gets scrolled top. how can avoid annoying behaviour?
n = 0; function addcontent() { div = document.getelementbyid('content'); for(var = 0; < 100; i++) { n++; div.innerhtml = div.innerhtml + n + '<br />'; } } </script> </head> <body> <div id="content"></div> <a href="#" onclick="addcontent()">more content</a>
ex: http://jsfiddle.net/hqp2q/
the problem here ,
when click on anchor link , onclick event handler registered element fired.
now default behavior anchor tag navigate href attribute of own.
in case both happens , url navigated "#". "#" acting bookmark , browser html element has id , same string after # in url.
so solution prepare problem , in onclick handler , pass event object , when onclick handler executed, utilize event object prevent default action of element click behaviour.
so code when modified.
<script> n = 0; function addcontent(e) { div = document.getelementbyid('content'); for(var = 0; < 100; i++) { n++; div.innerhtml = div.innerhtml + n + '<br />'; } e.preventdefault(); homecoming false; } </script> </head> <body> <div id="content"></div> <a href="#" onclick="addcontent(event)">more content</a>
see fiddle here : http://jsfiddle.net/ukrph/2/embedded/result/
javascript jquery
Comments
Post a Comment