YogeshChauhan . com

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

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 7 How to disable right click and drag and drop of images using jQuery? May 7 How to render Lists in React? May 7 What’s the difference between variables in CSS and SCSS (Sass)? May 7 How to define variables in SCSS (Sass)? May 7 How to show and hide an element on click in React? May 5 Use inline if to make a shorter conditional syntax in React

You might also like these

How to change CSS with JavaScript?CSSSome Useful Operators in The SQL WHERE ClauseSQL/MySQLThe actual difference between indexOf() and search() in JavaScriptJavaScriptHow to add Local State to a Class in React?React@mixin and @include in SCSS (Sass)SCSSIs monitoring an employee’s work on a computer a desirable or undesirable activity?MiscINTERSECT and EXCEPT in PostgresPostgresAmpersand (Parent Selector) in SCSS (Sass)SCSSHow to create a dynamic countdown using HTML and JavaScript?HTMLCreate a simple bar chart and column chart using pure CSS gridCSSPagination in CSS with multiple examplesCSSSelect statement in Postgres with examplesPostgres