window.location.hash = $(this).attr("href");
This is still going to cause the viewport to scroll; it’s more or less equivalent to just clicking the link. You can use the History API to push a new URL without causing it to be “visited”:
history.pushState(null, null, $(this).attr('href'));
If you need to support IE8 and earlier, it might work to hold onto the current scroll position:
var originalScroll = window.scrollY; // Grab window.scrollX if applicable
window.location.hash = $(this).attr("href");
window.scrollY = originalScroll;
You might have to put the window.scrollY = originalScroll
in a setTimeout
with a timeout of 0
, though.