by MichaelGG · 15y ago · 0 comments
Is it often the case that you want to wire up a click handler to link, but still want to follow the href? If not, why doesn't jQuery just automatically prevent navigation for links when handling the click event? Then for the few cases (confirming navigation, perhaps tracking user actions?) the programmer could explicitly indicate the continue through with navigation.
Having to write preventDefault() in each handler seems like unnecessary noise, doesn't it?
In life, rules need exceptions. In programming, it is usually nicer when there are as few as possible.
EDIT: If you desire to preventDefault on multiple handlers and you don't want to type it out every time you can simply add a line like
$("a").click(function(e){e.preventDefault()});
to your document and stop click event bubbling for every link.This is what delegate() was invented for.
$(document).delegate('a.nodefault', 'click', function(e){
e.preventDefault();
}
I'm using a .nodefault class selector such that it applies only to links marked with class="nodefault" - you might want to have links that should work normally.If you're using HTML5, using a data-yourapp-nodefault=true attribute might be even better as you shouldn't overload classes.
Incidentally, returning false; in a directly bound handler (which is was the original article was talking about) prevents exactly this suggestion here from working as the delegated handler on document would never see the click.