Disable Clicks on Empty Menu Items

When creating a dropdown menu in WordPress, often the parent menu item is used simply as a hover point to access the submenu, not as an actual link. When this is the case, we can use the following steps to indicate to the user that these menu items are not to be clicked.

1. Set the link URL

The first thing we’ll do (if this has not already been done) is set the URL of our empty links to # which will cause our link HTML to look like this:

<a href="#">Link text...</a>

Any link URL that starts with a # symbol is meant to reference a point on the current page. Using the # symbol by itself will typically take the user to the top of the current page. If the user is already at the top of the page, it will appear that the link doesn’t do anything. However, if the site has sticky header and the user clicks the link after scrolling down the page a little, it may surprise the user to be placed back at the top of the page.

2. Disguise clickability with CSS

We can use the following code to prevent the menu item from being underlined on hover and also prevents the mouse cursor from changing to a pointer when hovering over the menu item:

.menu-item a[href='#'] {
	text-decoration: none;
	cursor: default;
}

This code can be placed in the theme’s stylesheet, or in the Additional CSS section of the customizer.

3. Prevent the click with Javascript

Even without the styling to indicate that the user is hovering over a link, someone still might click it. To prevent the click from having an effect and placing the user back at the top of the page, we can use the following Javascript code:

// Disable empty menu item clicks
window.onload = function() {
	var anchors = document.querySelectorAll(".menu-item a[href='#']");
	for(var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		anchor.onclick = function(event) {
			event.preventDefault();
		}
	}
}

This code can be placed in the theme’s Javascript. It can also be placed using the customizer if the Additional JS plugin is installed.

…and that’s it!

Posted in , ,

Leave a Comment

Your email address will not be published. Required fields are marked *