As browsers automatically detect the hash
and take you to that position...
It occurs to me that you could first reset the scroll position to 0 and then made the smooth scrolling.
Something like...
if ( window.location.hash ) scroll(0,0);setTimeout( function() { scroll(0,0); }, 1);$(function() { $('.scroll').on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top + 'px' }, 1000, 'swing'); }); if(window.location.hash) { $('html, body').animate({ scrollTop: $(window.location.hash).offset().top + 'px' }, 1000, 'swing'); }});
Edit: Move the scroll(0,0)
outside $(function(){...});
to prevent flickering.
Also, Snippet with working example was added.
The effect is best appreciated when viewed in full screen
html, body { margin: 0; padding: 0; } .hidden-code { display: none; visibility: hidden; opacity: 0; } .header { background-color: #ccc; padding: 5px; } .header li { padding: 5px; margin: 5px; display: inline-block; } .articles > div { border: 1px solid; margin: 10px; padding: 250px 50px; background-color: #ccc; } div:before { content: attr(id); } .footer { text-align: center; }
<div class="header"> <ul> <li>page header title/navbar</li> <li><a class="scroll" href="#text-1">#text-1</a></li> <li><a class="scroll" href="#text-2">#text-2</a></li> <li><a class="scroll" href="#text-3">#text-3</a></li> <li><a class="scroll" href="#text-4">#text-4</a></li> <li><a class="scroll" href="#text-5">#text-5</a></li> <li><a class="scroll" href="#text-6">#text-6</a></li> <li><a class="scroll" href="#text-7">#text-7</a></li> <li><a class="scroll" href="#text-8">#text-8</a></li> </ul> </div> <div class="container"> <div class="content"> <div class="articles"> <div id="text-1"></div> <div id="text-2"></div> <div id="text-3"></div> <div id="text-4"></div> <div id="text-5"></div> <div id="text-6"></div> <div id="text-7"></div> <div id="text-8"></div> </div> </div> <div class="footer">company © 2015</div> </div> <div class="hidden-code"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script type="text/javascript"> if ( window.location.hash ) scroll(0,0); setTimeout( function() { scroll(0,0); }, 1); $(function() { $('.scroll').on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top + 'px' }, 1000, 'swing'); }); if(window.location.hash) { $('html, body').animate({ scrollTop: $(window.location.hash).offset().top + 'px' }, 1000, 'swing'); } }); </script> </div>