Created
January 21, 2026 15:11
-
-
Save mwender/4a9b0c6d4d844997978d70465946ea6a to your computer and use it in GitHub Desktop.
[Prevent Hash Link Clicks] Prevents clicks on "hash" links in navigation menus. #Elementor #WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Prevent hash-only links from updating the browser URL | |
| * | |
| * Finds all links with href="#" and prevents default click behavior | |
| * to avoid polluting the address bar with hash symbols. | |
| * | |
| * @since 1.0.0 | |
| */ | |
| ( function() { | |
| 'use strict'; | |
| /** | |
| * Handle click on hash-only links | |
| * | |
| * @param {Event} e The click event | |
| */ | |
| function handleHashClick( e ) { | |
| const href = this.getAttribute( 'href' ); | |
| // Only prevent default for links that are exactly "#" | |
| if ( href === '#' ) { | |
| e.preventDefault(); | |
| } | |
| } | |
| /** | |
| * Initialize hash link prevention | |
| */ | |
| function init() { | |
| // Find all links with href="#" | |
| const hashLinks = document.querySelectorAll( 'a[href="#"]' ); | |
| // Add click handler to each | |
| hashLinks.forEach( function( link ) { | |
| link.addEventListener( 'click', handleHashClick ); | |
| } ); | |
| } | |
| // Run on DOM ready | |
| if ( document.readyState === 'loading' ) { | |
| document.addEventListener( 'DOMContentLoaded', init ); | |
| } else { | |
| init(); | |
| } | |
| // Also run after a short delay to catch dynamically added menus | |
| // (useful for Elementor and other page builders) | |
| window.addEventListener( 'load', function() { | |
| setTimeout( init, 100 ); | |
| } ); | |
| } )(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment