Reputation: 2527
I want to perform an action when a user clicks on a div. However if he clicks on link within div, I want to send him directly to link. Now the href is being ignored.
<div id=myDiv>
some text
<a href="link1">my link</a>
some text
<a href="link2">my link</a>
some text
<a href="link3">my link</a>
<div>
$('.myDiv').live('click', function() {
console.log($(this));
// if clicked on link, the go directly to the link
....
// if clicked elsewhere on div, then perform another another action and return false
return false;
});
====== MY SOLUTION ====
I liked Rob's solution but the syntax was a bit vexing, so RTFM and came up with something similar that works for me.
$('.myDiv').live('click', function(event) {
var $target = $(event.target);
if( $target.is("a") ) {
return true;
}
else{
// do something else
return false;
}
});
Upvotes: 2
Views: 148
Reputation: 224913
Call stopPropagation()
when the links are clicked:
$('.myDiv').live('click', function(e) {
// Perform your action here
});
$('.myDiv a').live('click', function(e) {
e.stopPropagation();
});
Upvotes: 1
Reputation: 348992
Check the event.target
property. The code below does not execute return false
when an anchor is clicked.
$('.myDiv').live('click', function(event) {
....
// `return false` only if element != <a>
if(!$.nodeName(event.target, "a")) return false;
});
Upvotes: 1