JQuery: more on triggering events
[This post is not correct. I’ve tried to update its content in a new post which you can read here]
Now that we understand DOM level event models and their phases, it’s time to go back and to wrap up the triggers topic. In a previous post, we’ve already met the trigger method. Today we’re going to talk about the triggerHandle method.
The triggerHandle method will fire all event handlers of the indicated event for the *first* element contained on the node set. Unlike most JQuery’s methods, this method will return the result of the triggered handle instead of the traditional JQuery object. Notice that since v1.3, triggering will bubble through the DOM node tree (I’ve only updated my JS file recently so that’s why I said that the trigger method wouldn’t bubble in a previous post). The docs on this method say that you won’t get any bubbling, but my experiences have shown that you'll get bubbling.
To understand what’s going on, take a look at the following snippet:
<p>This is some hidden content</p>
<p>And more hidden content</p>
<input type="button" id="trigger" value="trigger" />
<input type="button" id="triggerHandler" value="triggerHandler" />
<script type="text/javascript">
$(function() {
$("*").not("input").click( function(evt){
alert(evt.currentTarget.tagName + " clicked");
return "hi";
});
$("#trigger").click(function() {
$("p").trigger("click");
});
$("#triggerHandler").click(function() {
alert($("p").triggerHandler("click"));
});
});
</script>
As you can see, we’ve got two paragraphs and two buttons. we’ve also setup a click handler for all elements in the page (with the exception of input buttons). If you click the trigger button, you’ll see that the event will be fired for all P elements and you’ll also get the “traditional” bubbling. If you click on the triggerHandler method, you’ll get the handler for the first P element of the wrapped set, then you’ll see an alert with that handler’s return value and then you’ll get the bubbling (which, according to the docs, shouldn’t happen). [The previous information regarding bubbling is incorrect. Please read the next post for the correct info and understand why I’ve made this incorrect claim. Sorry for the mess.]
And that’s it for today. Keep tuned for more on JQuery.