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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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 list all PHP variables to debug the script?PHPRecursive WITH Queries in Postgres (Common Table Expressions)PostgresHow to check if the page is single post page in WordPress?WordPressCheck if mixin is being called in a style rule or not in SCSSSCSSHow to display and animate image on scroll using JavaScript?JavaScriptWhat’s a repository on Github?MiscellaneousModules and its Core features in JavaScriptJavaScriptA Quick Comparison of JOIN and Subquery in SQLSQL/MySQLHow to Make CSS Lists Bullets Smaller?CSSCheck if any column has NULL values in PostgresPostgresArguments in @mixin rules in SCSS (Sass)SCSSHow to create a simple digital clock using JavaScript?JavaScript