Reputation:
I'm trying to handle .click action but exclude links from it so that you could click on a link in an element without firing .click.
I've got no clue how to do that. I've tried z-indexes, position: absolute, relative but nothing worked.
<style>
div {
background: yellow;
height: 200px;
}
</style>
<script>
$(window).load(function(){
$(function() {
$( "div" ).click(function() {
alert( "Click handler." );
});
});
});
</script>
</head>
<body>
<div>
<a target="_blank" href="http://stackoverflow.com/">Link</a>
</div>
</body>
</html>
Any help? Thanks!
Upvotes: 1
Views: 69
Reputation: 1146
You can check the 'currentTarget' vs 'target', the currentTarget is the exactly the object that you putted the bind, and the 'target' is the element that is clicked, that could be any element inside your div. This way you will ensure that the event will only be fired when the click is in the div.
$(function() {
$('div').bind('click', function(ev) {
if($(ev.currentTarget).get(0) == $(ev.target).get(0)) {
alert('clicked');
};
});
});
Upvotes: 1
Reputation: 206078
$( "div" ).click(function( e ) {
if(e.target.tagName=="A") e.preventDefault();
alert( "Click handler." );
});
Upvotes: 0
Reputation: 388326
$(function () {
$("div").click(function (e) {
if (!$(e.target).closest('a').length) {
alert("Click handler.");
}
});
});
Demo: Fiddle
Upvotes: 0
Reputation: 318182
check if the clicked element is an anchor
$(function() {
$( "div" ).click(function(e) {
if (e.target.tagName.toLowerCase() != 'a')
alert( "Click handler." );
});
});
or prevent the click from anchors to propagate up to parent elements
$(function() {
$( "div" ).click(function(e) {
alert( "Click handler." );
});
$('a').click(function(e) {
e.stopPropagation();
})
});
or check of the clicked element is an anchor, or within an anchor
$(function() {
$( "div" ).click(function(e) {
if (! $(e.target).closest('a').length)
alert( "Click handler." );
});
});
Upvotes: 2