Yogesh Chauhan's Blog

How to create a cross-browser smooth scrolling with jQuery?

in jQuery on October 17, 2020

We saw how to create a smooth scrolling using CSS in this post: How To Create A Smooth Scrolling Effect With CSS?

But scroll-behavior property is not supported by all browsers so we can use JavaScript or jQuery to achieve cross-browser smooth scrolling solution.

Solution using ID


$(document).ready(function () {
  $("#elementID").on("click", function (event) {
    event.preventDefault();
    var element = $(this);
    $("html, body").animate(
      {
        scrollTop: element.offset().top,
      },
      800
    );
  });
});

Solution using a tag


$(document).ready(function () {
  $("a").on("click", function (event) {
    if (this.hash !== "") {
      event.preventDefault();

      var hash = this.hash;

      $("html, body").animate(
        {
          scrollTop: $(hash).offset().top,
        },
        800,
        function () {
          window.location.hash = hash;
        }
      );
    }
  });
});

Source: w3schools


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to get category name using post id in WordPress?WordPressHow to include CSS and JavaScript files in your WordPress plugin?WordPressRIGHT JOIN in PostgresPostgresWhat are Big Data Clusters in SQL Server?SQL/MySQLConditional operator in JavaScript (aka ternary operator)JavaScriptHow to Clone Objects in PHP?MiscellaneousHow to make a curtain slider using jQuery and CSS?CSSHow to list all PHP variables to debug the script?PHPWordPress: How to query all posts from custom post type and display them in a list?WordPressWhat’s a Log File and What are Log File Monitors?Miscellaneous3 Types of Arrays in PHPPHPFor In Loop in Swift for BeginnersSwift