1

Demo on jsfiddle.net

HTML:

<a href='http://www.jsfiddle.net'><span>link</span></a>

Script:

$('span').click(function(event) {
  window.open('http://www.google.com');
  event.stopImmediatePropagation();
  //The line below does prevent jsfiddle.net from loading on the right.
  //event.preventDefault();
});
$('a').click(function() {
  //This function is not triggered as event propagation has been stopped.
  alert('You will never see this.');
});

Clicking on "link" in the demo will cause both google.com and jsfiddle.net to be opened. Here comes my question: Why is the default behavior of <a> (opening jsfiddle.net in this case) inherited by its children (<span> in this case)? Are there any specifications I can refer to? Thanks in advance.

zanetu
  • 3,740
  • 1
  • 21
  • 17

2 Answers2

2

Why is the default behavior of <a> inherited by its children?

Because it makes sense :-) Every click on a link or its descendants does trigger an event whose default action is to activate the link.

Are there any specifications I can refer to?

Check Default actions and cancelable events in the DOM level 3 spec for an explanation of cancellation. However, DOM3 does not specify any default actions on its own.

Those are done in the HTML 5 spec, for clicks specifically in the Interactive Content section:

When a pointing device is clicked, the user agent must run these steps:

  1. [Set some flags]
  2. Let e be the nearest activatable element of the element designated by the user, if any. To obtain that, check whether the target has a defined activation behavior. If it does, take it, if it doesn't (and has a parent element) then repeat the checking with the parent element of the target.
  3. If there is an element e, run pre-click activation steps for it if any.
  4. Dispatch the required click event.
  5. If there is an element e and the click event is not canceled, run post-click activation steps for it if any.
  6. If there is an element e and the event is canceled, run canceled activation steps for it if any.
  7. [Reset flags]

The activation behaviour is defined by the elements themselves, e.g at the <a> element to get and follow a hyperlink.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Please look at this answer here:

does e.stopPropagation() in jquery works on anchor tag

You may combine with event.preventDefault(); in order to get the desired behaviour. StopPropagation prevent events to be fired but not default behaviours such navigate to a page when clicking a <a> tag.

Community
  • 1
  • 1
sabotero
  • 4,265
  • 3
  • 28
  • 43
  • Rather than saying that it stops events from being fired it's more correct to say that it stops events from bubbling up to parent nodes. http://www.quirksmode.org/js/events_order.html – slebetman Oct 28 '13 at 11:05