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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to convert an object from API to JSON array in Angular 9?AngularSocial Media Colors: LESS VariablesMiscellaneousOverview of Drupal and how it worksDrupalThe Sort and Compare Functions in JavaScriptJavaScriptVariables and Distance Functions in SCSS (Sass)SCSSSolution to “NullInjectorError: No provider for module” in Angular 9AngularHow to create a Bootstrap style accordion using CSS and JavaScript?CSSHow to get the first element with a class name xyz using JavaScript?JavaScriptUse eq() method in jQueryjQuery4 ways to create Date Objects in JavaScriptJavaScriptCanvas Drawing in HTML5HTMLHow to read Standard Input in Swift?Swift