How to implement a smooth page scroll to anchor links with jQuery



Image not found!!

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:

  1. Include jQuery in your HTML file. You can either download it and host it locally or use a CDN. Add the following line to your <head> section:
html
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  1. Create anchor links in your HTML with corresponding IDs for the target sections. For example:
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>
  1. Add jQuery code to handle smooth scrolling. You can include the following script in your HTML or an external JavaScript file:
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.