Before I start writing huge swathes of code that don’t work I thought I’d ask this question.
event.preventDefault() only cancels the default action of the click event doesn’t it?
Theoretically I should be able to bind mutiple click event handlers in jQuery to a given target to perform different actions like Ajax posts and Google tracking.
Am I wrong?
It cancels the browser’s default action of the event (not just the
clickevent) (W3C docs, jQuery docs). So for instance, in the formsubmitevent, it prevents the form being submitted by the browser. It doesn’t stop anything you’re doing in code, and it doesn’t stop bubbling; that’s whatstopPropagationis for (W3C docs, jQuery docs).So say you have a link in a
div, and you have theclickevent hooked on both the link and thediv. If the link’s event handler callspreventDefault, the browser won’t do its default action (following the link), but the event continues to bubble up the DOM to the link’s parent element, thediv, and so you’ll see the event on yourclickhandler there, too. Any actions you’re taking in code in either handler will be unaffected by your callingpreventDefault.In your comment below, you ask about multiple handlers on the same element. Neither
preventDefaultnorstopPropagationaffects those, they’ll still get fired…unless you usestopImmediatePropagation, which tells jQuery to stop the event dead in its tracks (but doesn’t prevent the browser’s default action).I should probably round this out by saying that if you return
falsefrom your event handler, that tells jQuery to prevent the default and stop bubbling. It’s just like callingpreventDefaultandstopPropagation. It’s a handy shortcut form for when your event handler is taking full control of the event.So, given this HTML:
Example 1:
Example 2:
Example 3 (you’ll only rarely see this):
Example 4: