Smooth scrolling isn’t functioning properly when you click on the navigation menu links that lead to different sections on the same page? Below is the solution
Will make the smooth scroll easily by using below steps
Step 1: HTML
Create a straightforward one-page layout that includes internal navigation links
<nav>
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>
<section id="about">
<h2>About Us</h2>
<p>Some content...</p>
</section>
<section id="services">
<h2>Our Services</h2>
<p>More content...</p>
</section>
Step 2: CSS
/* style.css */
body {
font-family: sans-serif;
scroll-behavior: auto; /* will override with jQuery */
}
nav {
position: fixed;
top: 0;
background: #333;
width: 100%;
padding: 10px;
text-align: center;
}
nav a {
color: white;
margin: 0 15px;
text-decoration: none;
}
section {
height: 100vh;
padding-top: 60px;
}
Step 3: jQuery
// script.js
$(document).ready(function () {
$('nav a').click(function (e) {
e.preventDefault(); // Stop default jump
const target = $(this).attr('href'); // Get the section ID
$('html, body').animate(
{
scrollTop: $(target).offset().top
},
800 // Duration in milliseconds
);
});
});
Hope this helps. Please mention in comments if any queries
Leave a Reply