📜  jquery smooth scool - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:11.629000             🧑  作者: Mango

jQuery smooth scroll - Javascript

Introduction

When we have a web page with long content, it can be difficult for users to navigate to the specific sections they need to reach. The usual way of solving this problem is by using hyperlinks pointing to the specific section, but the user experience may not be optimal as it may jump abruptly between sections. To enhance the user experience, we can add a smooth scrolling effect to our hyperlinks using jQuery.

What is jQuery?

jQuery is a fast, lightweight, and feature-rich JavaScript library. It simplifies HTML document manipulation, event handling, animation, and AJAX interactions for fast web development.

Smooth Scroll

Smooth scroll is a JavaScript technique that animates scrolling to anchor links. Instead of it jumping directly, the scroll will transition smoothly, giving a better user experience. It involves adding a small piece of code that overrides the default hyperlink behavior and adds smooth scrolling to the page.

How to use jQuery smooth scroll
  1. Include jQuery in your HTML file. You can use a CDN link or download it and include it in your application directory.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  1. Add the following JavaScript code after the jQuery library script tag. This code will add smooth scrolling behavior to hyperlinks that contain href attribute values starting with #:
$(document).ready(function(){
  $('a[href^="#"]').on('click', function(event) {
    var target = $(this.getAttribute('href'));
    if( target.length ) {
        event.preventDefault();
        $('html, body').stop().animate({
            scrollTop: target.offset().top
        }, 1000);
    }
  });
});
  1. Add a hyperlink with an id attribute to the section you want to navigate to. For example:
<h2 id="section-1">Section 1</h2>
  1. Add a hyperlink to this section in the navigation menu or anywhere on the page using the following code:
<a href="#section-1">Go to Section 1</a>
Conclusion

jQuery smooth scroll is a simple and effective way to add smooth scrolling effects to navigation links on long web pages. It provides a better user experience by making navigation more fluid and enjoyable. With this snippet, you can quickly add this feature to your web page and impress your users.