Javascript Example: Preventing Page Scroll/Hiccups on Refresh or Navigation using ScrollSneak
Last updated:Although the new trend is to use Ajax as much as possible in your application and websites (so as to reduce the number of round-trips to the server and to provide an overall better, more fluid experience to users), sometimes it's not possible to do so and we must make do with what we have.
One situation where a regular (non-ajax) solution would be advised would be when you want to enable users to access different states using the browser back button
Users usually get annoyed when they have to navigate through many pages (maybe a grid) and, with every new page, the page gets scrolled to the initial position and they have to scroll down for every page.
This can be easily solved using ScrollSneak by Peter Coles.
You can download the code from this gist. Download it into a file called scroll_sneak.js.
This is how you could use ScrollSneak to prevent the page from scrolling up:
<!DOCTYPE html>
<html>
<head>
<!--i'm using jquery too -->
<script type="text/javascript" src="path/to/jquery.js"></script>
<!-- include scroll_sneak.js -->
<script type="text/javascript" src="path/to/scroll_sneak.js"></script>
<!-- now activate scroll sneak -->
<script type="text/javascript">
$(document).ready(function(){
var sneaky = new ScrollSneak(location.hostname);
// you want to prevent scrolling when form #my-form is submitted
document.getElementById('my-form').onsubmit = sneaky.sneak;
// or maybe you want to prevent scrolling whenever any link within
// a list-option is clicked:
$('li a').each(function(){
// note the use of 'this' instead of '$(this)', because we
// want the raw element, not the jQuery object
this.onclick = sneaky.sneak;
});
});
</script>
</head>
<body>
<!-- your content, like the forms and the links -->
...
</body>
</html>