13

On my web page I have a list of files.

Each file is in it's own container div (div class="file"). Inside the container is a link to the file and a description.

I wanted to allow a user to click anywhere on the container to download the file. I did this by adding a click event to the container and retrieving the href of the child link.

As the file opens in a new window, if the user actually clicks the link, the file opens twice.

So I need to prevent the parent container click event from firing when the hyperlink is clicked. Would the best way of doing this be to add a click function to the hyperlink to0 and set event.stopPropagation? Presumably this would then stop the event from bubbling up to the container.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ben Foster
  • 34,340
  • 40
  • 176
  • 285

3 Answers3

19

In the Microsoft model you must set the event’s cancelBubble property to true.

window.event.cancelBubble = true;

In the W3C model you must call the event’s stopPropagation() method.

event.stopPropagation();

Here's a cross-browser solution if you're not using a framework:

function doSomething(e) {
    if (!e) e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}
Rudey
  • 4,717
  • 4
  • 42
  • 84
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
11

Yes, use stopPropagation. See: Prevent execution of parent event handler

Community
  • 1
  • 1
pix0r
  • 31,139
  • 18
  • 86
  • 102
3

Thanks for the help.

I was using jQuery but it's good to know a non-framework solution.

Added the following for the links:

$(".flink").click(function(e) {
    e.stopPropagation();
});
YakovL
  • 7,557
  • 12
  • 62
  • 102
Ben Foster
  • 34,340
  • 40
  • 176
  • 285
  • Thanks! I was having exactly this problem, which was quite annoying to debug and this solved it. In my case I had a click handler for .pub and then added the line $(".pub a").click(function(e) {e.stopPropagation();}); – daveagp Jul 26 '11 at 14:58
  • doesn't returning false from the event handler function have the same effect? – Johnus Oct 01 '11 at 12:54
  • @Johnus - no it doesn't - see http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ – Ben Foster Oct 13 '11 at 09:50