4 ms·
I'm not very well versed with JavaScript/jQuery, so perhaps my thinking here is completely off. Is it often the case that you want to wire up a click handler t
by MichaelGG 16y ago
I'm not very well versed with JavaScript/jQuery, so perhaps my thinking here is completely off.
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?
- fooandbarify 16y agoOne 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 16y 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 16y 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.