I have a website with multipages .. So i need a code for navigating to another page with smooth scrolling after loading on a specific id or section on another page
e.g. in the navbar i have multipages so i will make a page contain 4 links from the navbar .. so i need when i click on the link in the navbar navigate me to the page containing this links and smooth scroll down to the section contains this link i clicked on it
I made't with only html but without the smooth scrolling .. i just click on the link in the navbar and it navigate me to the specified section that contains this link info. in the other page
I don't know if my question is clear enough but i hope so
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');
}
});
In you CSS file Simply add-
html{
scroll-behaviour : smooth;
}
And specify the ID in the href as
href="file_where_the_element_is.html#ID_of_the_element
Eg:
<a href="index.html#contentID>
Its that SIMPLE!!! No JS, JQuery required. Only CSS and HTML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With