0

I'm very new to jquery and I'm currently reading "learning jQuery" I have a question regarding event capturing and event.target.

I have the html code like this:

<div id="switcher" class="switcher">
        <h3>Style Switcher</h3>
        <button id="switcher-default">
          Default
        </button>
        <button id="switcher-narrow">
          Narrow Column
        </button>
        <button id="switcher-large">
          Large Print
        </button>
</div>

According to event capturing with jQuery jQuery doesn't support event capturing and only support bubbling. Which means, if both buttons and div element are binded to the click event and when I click on the button, button's click will call first, then the div, and since event capturing is not supported, which means if I click on the div area, button's click function will NOT be called.

However, if I add something like this:

$("#switcher").click(function(event) {
    alert(event.target);
});

and if I click on the button, the event target will be the button. If the selector $("#switcher") only select the div element, then how come when I click on the button, it alerts the event.target? I thought when I click on the button, the above jQuery will not be called at all?

Community
  • 1
  • 1
Josh
  • 692
  • 2
  • 9
  • 38
  • 1
    Because events bubble. When you click on teh button, the event happens on the button, and then bubbles up to the div. – Kevin B Jul 18 '13 at 21:39
  • And that's why `if (event.target === this)` works to avoid that issue. – adeneo Jul 18 '13 at 21:40
  • what I don't understand is, I got that alert message when I clicked on the button, even I didn't add any click event to the button – Josh Jul 19 '13 at 13:54

0 Answers0