JSFiddle - React, Tailwind, and code Playground

by huppen

HTML

<div id="click"><a href="#abc"></a><p>Scroll to hash on page load and remove hash/or scroll to click in href </p></div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="scroll"><p>Div to scroll</p></div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="abc"><p>Div abc to scroll</p></div>

JavaScript

//Scroll to hash on page load and remove hash/or scroll to click in href 
$(document).ready(function(){
  var target = window.location.hash,
      target = target.replace('#', '');

	//optional for testing
  target = "scroll"; 
      
  // delete hash so the page won't scroll to it
  window.location.hash = "";

  //delete even the hash at the end
  var uri = window.location.toString();
  if (uri.indexOf("#") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("#"));
    window.history.replaceState({}, document.title, clean_uri);
  }

  // now whenever you are ready do whatever you want
  // (in this case I use jQuery to scroll to the tag after the page has loaded)
  $(window).on('load', function() {
      if (target) {
          $('html, body').animate({
              scrollTop: $("#" + target).offset().top -30
          }, 500, 'swing', function () {});
      }
  });
  
  $("#click").on('click', function() {
  var scrollto = $(this).find("a").attr("href"),
      scrollto = scrollto.replace('#', '');
      if (scrollto) {
          $('html, body').animate({
              scrollTop: $("#" + scrollto).offset().top -30
          }, 500, 'swing', function () {});
      }
  });
});