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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to make HTML form interactive and using CSS?CSSSelf-Driving and Intelligent NetworksMiscHow to vertically align a html radio button to it’s label?CSSJavaScript Number MethodsJavaScriptHow to create a dynamic countdown using HTML and JavaScript?HTML@forward modules with a prefix in SCSS (Sass)SCSSSQL GROUP BY StatementSQL/MySQLWordPress: How to get field values in Advanced Custom Fields?WordPressUPDATE and DELETE Statements in PostgresPostgresHow to add onclick event to html elements dynamically using JavaScript?JavaScriptLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLHow to add a Pie Chart in Angular App?Angular