Prevent default link if href has a hash

I am working on a WordPress theme using custom taxonomies and custom post_types. One problem that I notice if you’ve allowed these to be registered to the navigation menu the archive or singular tax or type is still missing. For example if I register the post_type snippets, and add a post or two like snippet one & snippet two, the two posts will register in the navigation menu, but the parent or archived page will not. Luckily there are custom links. So we’ll work with that for the time being.

In this example I am going to add to the menu a custom link called Snippets and add the href of # (although I can write it as the actual permalink if using WordPress greater than 3.1 and my post_type is using has_archive). I am choosing to just make it a placeholder for drop-down menus, but I don’t like when someone clicks a link and it just adds a # to the ending URL.

So, without further adieu, the jQuery code snippet:

/* Prevent default if menu links are "#". */
$j('nav a').each( function() {
	var nav = $j(this); 
	if( nav.length > 0 ) {
		if( nav.attr('href') == '#' ) {
			//console.log(nav);
			$j(this).click(
				function(e) {
					e.preventDefault();
				}
			);
		}
	}
});  

Note, I am using $j. You can choose to use this, $ or jQuery for your prefix. Be sure to change the nav a to your corresponding anchor with prefix.

Overview

This line is finding all anchors, which happen to be nested in nav elements:

$j('nav a').each( function() {

This line defines the variable, then checks if one exists and then if that anchors href attribute is a hash tag.

var nav = $j(this); 
	if( nav.length > 0 ) {
		if( nav.attr('href') == '#' ) {

And finally we add the click function and attach it to the element. We then use preventDefault to disallow the normal link click.

$j(nav).click(
				function(e) {
					e.preventDefault();
				}
			);
Austin
Austin

πŸ’πŸ½β€β™‚οΈ Husband to Jeana.
⚾️ Dodgers & Brewers.
πŸ’» PHP Engineer.
πŸŒπŸΌβ€β™‚οΈGolfer; ~14 HDC.
🌱 Hydroponic Gardner.
🍿 Plex nerd.
πŸš™ '15 WRX, '22 Model 3 LR, & '66 Corvette C2.

Follow me on Twitter @TheFrosty & Instagram @TheFrosty.

Articles: 292

One comment

  1. I know it’s old post, but if someone want simplest method, here it is:

    $('a[href^=#]').click(function(e){e.preventDefault();});

    The ‘a[href^=#]’ part is translated like: all link elements(a) which hrefs begins with hash tag(#);

    so e.g.: # or #link will be ‘prevented’.
    BUT: It doesn’t prevent page scrolling to certain id (id=”link” in this case), because it’s non-programmable browser behavior.

Comments are closed.