JQuery: more on the triggerHandler method

In the previous post I’ve shown you some code on how to use the triggerHandler method. At the time, I said that events would bubble even though the docs say that they won’t. I based my conclusions on a small simple test I’ve written. ingmar added more information on a comment saying that if you have a more complex tree, you won’t get the “correct” bubbling. For instance, with the following structure:

    <p>This is some hidden content</p>
    <p>And more hidden content</p>

you’ll get the following bubbling: P->BODY->HTML. So, what’s happening here? Well, it’s simple: I was wrong. The fact is that the bubbling I was seeing was coming from my button’s click event and not from the triggered element. Let’s take another peek at the script code I’ve written:

<script type="text/javascript">
    $(function() {
        $("*").not("input").click(function(evt) {
            alert(evt.currentTarget.tagName + " clicked");
            return "hi";
        $("#trigger").click(function() {
        $("#triggerHandler").click(function() {

As you can see, we’re hooking up all the elements’ click event (excluding inputs) with an anonymous function that displays an alert message with the tagName of the current target element. Now, when I wrote the small sample, I concentrated on the P’s click event and this was what I saw:


Since my initial markup looked like this:

<p>This is some hidden content</p>
<p>And more hidden content</p>

I completely forgot that the click event of the button would also propagate through the tree until it reaches the top element. Notice that when you dispatch an event from within an existing handler, that handler will be “suspended” until that “new” event is completely dispatched. When that happens, the “previous” event that was in “stand by” wakes up and goes through its normal lifecycle. So, if I had written this code:

$("#triggerHandler").click(function(evt) {

it would have been obvious that there was no bubbling coming from the P’s click event that has been dispatched through that anonymous function. I guess that the moral of the story is that I should pay more attention to the samples I’m writing during my JQuery tests. Thanks go to ingmar for putting me in the right track. Keep tuned for more on JQuery.


~ by Luis Abreu on August 5, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: