Modern web browsers have the ability to detect the hash in the URL and automatically navigate to that specific section. However, if you prefer smooth scrolling instead of instant jumping, you can reset the scroll position to the top and then apply smooth scrolling.
Include the following script:
// Scroll to top immediately
if (window.location.hash)
scroll(0,0);
// Resolve some browser issues
setTimeout(function(){scroll(0,0);},1);
Now, attempt to access the anchor from another page and observe how the browser smoothly scrolls to the top without abruptly jumping to the anchor element.
Next, implement smooth scrolling:
$(function(){
// Handle click event
$('.scroll').on('click',function(e){
e.preventDefault();
$('html,body').animate({
scrollTop:$($(this).attr('href')).offset().top + 'px'
},1000,'swing');
});
// Smooth scroll when accessed via anchor in URL
if(window.location.hash){
// Scroll smoothly to the anchor id
$('html,body').animate({
scrollTop:$(window.location.hash).offset().top + 'px'
},1000,'swing');
}
});
Following these steps will ensure a seamless experience. You will be directed to the anchor element on another page with a smooth scrolling effect.
Complete script:
// Scroll to top immediately
if (window.location.hash)
scroll(0,0);
// Resolve some browser issues
setTimeout(function(){scroll(0,0);},1);
$(function(){
// Handle click event
$('.scroll').on('click',function(e){
e.preventDefault();
$('html,body').animate({
scrollTop:$($(this).attr('href')).offset().top + 'px'
},1000,'swing');
});
// Smooth scroll when accessed via anchor in URL
if(window.location.hash){
// Scroll smoothly to the anchor id
$('html,body').animate({
scrollTop:$(window.location.hash).offset().top + 'px'
},1000,'swing');
}
});