Remove the #id Hash From the URL on Anchor Link Click

Quick Summary
- A jQuery click handler cancels the default jump with event.preventDefault() and animates the scroll, so the hash never reaches the URL.
- Give the link the btn-click class and an href pointing to the section's ID, and enqueue your script with jquery as a dependency.
- Keep the href and target ID in sync, since a missing target throws an error, and subtract a fixed header's height from offset().top.
When a link points to a section on the same page, such as #services-link, the browser jumps to that section and adds the #services-link hash to the URL in the address bar. This jQuery snippet scrolls smoothly to the section instead and keeps the hash out of the URL.
The link
Give the link the btn-click class and set its href to the ID of the section it should scroll to. The page needs an element with that ID, for example a section with id="services-link".
<a class="btn-click" href="#services-link">OUR SERVICES</a>The jQuery
Add this to your theme’s JavaScript file. jQuery must be loaded first; in WordPress, enqueue your script with jquery as a dependency.
jQuery(document).ready(function($) {
$(".btn-click").click(function(event) {
event.preventDefault();
$('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
} );
} );event.preventDefault()cancels the default jump, which is why the hash never reaches the URL.this.hashis the#services-linkpart of the link, and$(this.hash)selects the target element.offset().topis the target’s distance from the top of the page, andanimate()scrolls bothhtmlandbodythere, because browsers differ in which one scrolls.1000is the scroll duration in milliseconds.jQuery(document).ready(function($) { … })lets you use$inside the function, since WordPress loads jQuery in no-conflict mode. Without it, you’d hit TypeError: $ is not a function in WordPress.
If the target ID doesn’t exist on the page, the script throws an error, so keep the href and the ID in sync. With a fixed header, subtract its height from offset().top so the section title isn’t hidden behind it. If the WordPress admin bar also covers a fixed header for logged-in users, see offsetting a fixed header for the admin bar.
Related articles
- changing the URL without a page reload: for when you do want the address bar to update
