Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how to preventDefault on a child element from within parent event handler

Suppose I have HTML like this:

<div>
    <a href="http://google.com">Google</a>
</div>

And I have an event handler like this (suppose I have jQuery available):

$('div').on('click', function(ev) {
    // ...
});

Is it possible, from within that event handler, to prevent the default action of the <a> link? Or is it too late? (In other words, am I required to attach an event on the <a> or lower to prevent the default link action, or is it possible to stop it in the above handler).

As said above, I have jQuery available if the solution requires it.

like image 214
Ben Lee Avatar asked May 11 '12 20:05

Ben Lee


2 Answers

This will definitely work:

$('div').on('click', "a", function(e) {
    e.preventDefault();
});

Here's a fiddle: http://jsfiddle.net/xvKNC/1/

Hold on. this seems to work fine for me in Chrome

// prevent default on every click in the div
$('div').on('click', function(ev) {
    ev.preventDefault();
});

See the updated fiddle: http://jsfiddle.net/xvKNC/2/

like image 177
Jamund Ferguson Avatar answered Sep 29 '22 06:09

Jamund Ferguson


It seems to work:

$('div').on('click', function(ev) {
    ev.stopImmediatePropagation();
    ev.preventDefault();

});

JSFiddle: http://jsfiddle.net/3yFfC/

like image 23
strah Avatar answered Sep 29 '22 08:09

strah