Modern Browsers detect the hash in the url and then automatically open that part. So, if you want to scroll smoothly to that part instead, you first need to reset the scroll position to 0 and then add smooth scrolling.
Add the following script
// direct browser to top right away
if (window.location.hash)
scroll(0,0);
// takes care of some browsers issue
setTimeout(function(){scroll(0,0);},1);
Now, try to access the anchor from other page and you will notice that the browser takes you to top of the page without scrolling to the anchor element.
Now, add smooth scroll:
$(function(){
//your current click function
$('.scroll').on('click',function(e){
e.preventDefault();
$('html,body').animate({
scrollTop:$($(this).attr('href')).offset().top + 'px'
},1000,'swing');
});
// if we have anchor on the url (calling from other page)
if(window.location.hash){
// smooth scroll to the anchor id
$('html,body').animate({
scrollTop:$(window.location.hash).offset().top + 'px'
},1000,'swing');
}
});
It will work perfectly now. You will be taken to the anchor element in other page with scrolling smoothly to that part.
Complete code:
// direct browser to top right away
if (window.location.hash)
scroll(0,0);
// takes care of some browsers issue
setTimeout(function(){scroll(0,0);},1);
$(function(){
//your current click function
$('.scroll').on('click',function(e){
e.preventDefault();
$('html,body').animate({
scrollTop:$($(this).attr('href')).offset().top + 'px'
},1000,'swing');
});
// if we have anchor on the url (calling from other page)
if(window.location.hash){
// smooth scroll to the anchor id
$('html,body').animate({
scrollTop:$(window.location.hash).offset().top + 'px'
},1000,'swing');
}
});