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();
				}
			);