To implement smooth page scrolling to anchor links using jQuery, you can use the animate
function to smoothly scroll to the target element. Here's a simple example:
<head>
section:html<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
html<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<section id="section1">
<!-- Content for Section 1 -->
</section>
<section id="section2">
<!-- Content for Section 2 -->
</section>
html<script>
$(document).ready(function() {
// Smooth scroll to anchor links
$('a[href^="#"]').on('click', function(event) {
event.preventDefault();
var target = $(this.getAttribute('href'));
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 800);
}
});
});
</script>
This script listens for clicks on anchor links that start with the #
symbol and smoothly scrolls to the target section.
Adjust the 800
in the animate
function to control the duration of the animation. You can customize the script further based on your specific needs.
Remember to adapt the code to fit your HTML structure and requirements.