Smooth Onpage Scrolling to Anchor Links
by jay prakash
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smooth Scrolling with jQuery</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
</nav>
<section id="section1"> <h2>Section 1</h2> </section>
<section id="section2"> <h2>Section 2</h2> </section>
<section id="section3"> <h2>Section 3</h2> </section>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
CSS
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
text-align: center;
}
nav {
position: fixed;
top: 0;
width: 100%;
background: #333;
padding: 10px 0;
}
nav ul {
list-style: none;
padding: 0;
}
nav ul li {
display: inline;
margin: 0 15px;
}
nav ul li a {
color: white;
text-decoration: none;
}
section {
height: 100vh;
padding-top: 60px;
}
#section1 { background: lightblue; }
#section2 { background: lightcoral; }
#section3 { background: lightgreen; }
JavaScript
$(document).ready(function(){
$("nav a").on("click", function(event) {
event.preventDefault();
var target = this.hash;
$('html, body').animate({
scrollTop: $(target).offset().top
}, 1000);
});
});