Is it possible to remove the hash from window.location
without causing the page to jump-scroll to the top? I need to be able to modify the hash without causing
Have you tried return false;
in the event handler? jQuery does something special when you do that, similar to, but AFAIK more impactful, than e.preventDefault
.
Setting window.location.hash to empty or non-existing anchor name, will always force the page to jump to top. The only way to prevent this is to grab the scroll position of the window and set it to that position again after the hash change.
This will also force a repaint of the page (cant avoid it), though since it's executed in a single js process, it won't jump up/down (theoretically).
$('<a href="#123">').text('link').click(function(e) {
e.preventDefault();
window.location.hash = this.hash;
}).appendTo('body');
$('<a href="#">').text('unlink').click(function(e) {
e.preventDefault();
var pos = $(window).scrollTop(); // get scroll position
window.location.hash = '';
$(window).scrollTop(pos); // set scroll position back
}).appendTo('body');
Hope this helps.