YogeshChauhan.com
How to create a cross-browser smooth scrolling with jQuery?
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

Leave a Reply

Most Read

#1 How to set opacity or transparency using CSS? #2 Pagination in CSS with multiple examples #3 How to check if radio button is checked or not using JavaScript? #4 How to make HTML form interactive and using CSS? #5 How to uninstall Cocoapods from the Mac OS? #6 How to add Read More Read Less Button using JavaScript?



Recently Posted

Feb 24 How to modify the latest post array using get_posts() in WordPress? Feb 22 WordPress: How to get ACF field values from another post? Feb 22 WordPress: How to print ACF repeater field values? Feb 22 WordPress: How to print ACF array field values? Feb 21 WordPress: How to get field values in Advanced Custom Fields? Feb 21 WordPress: How to add a Search Icon in Menus with toggle effect using jQuery?



You might also like these

How to create a smooth scrolling effect with CSS?CSSThe fundamental difference between HAVING and WHERE clauses in PostgresPostgresThe SELECT DISTINCT Statement in SQLSQL/MySQLHow to Commit and Rollback Changes in SQL?SQL/MySQLJavaScript Input Validation Theme Park Example using throw StatementJavaScriptConditional operator in JavaScript (aka ternary operator)JavaScriptINNER JOIN in PostgresPostgresCanvas Drawing in HTML5HTMLDISTINCT ON: The confusing, unique and useful feature in PostgresPostgresHow to apply style to a specific child element using CSS?CSSFive common features of Angular template syntax (with examples)Angulartransform-origin Property in CSSCSS