14 ms·
One counterargument might be that it is unhelpful to prevent default event behaviour depending on its type or target. Events normally bubble - that is the expec
by fooandbarify 15y ago
One counterargument might be that it is unhelpful to prevent default event behaviour depending on its type or target. Events normally bubble - that is the expected behaviour. Clicks are just another event.
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.
- MichaelGG 15y agoRight I can see how it's a cleaner conceptual model, but less boilerplate code is also valuable. But in your edit, I see how easy it is to add it by hand, which is far preferable. Thanks!
- pilif 15y agodon't do that on IE where there are potentially a lot of <a>-tags. IE behaves really, really badly once a selector matches a large amount of elements (there must be something O(n^2) going on somehwere). 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.