Reputation: 142
I have a postcard feature that basically animates an overlay div then puts a postcard in above it. The HTML is something along the lines of:
<div id="overlay">
<div class="postcard">
<p>This is a postcard</p>
<a href="#">close</a>
</div>
</div>
My jquery looks like this:
$('#overlay, .postcard a').click(function(){ doSomething() })
I want my event handlers to pickup clicks on the overlay div and the postcard anchor only.
Currently a click is identified on all elements, including the postcard div.
Any help would be very much appreciated.
Upvotes: 1
Views: 3510
Reputation: 14161
click events will be fired if an element or its descendants is clicked.
you can use target of events, which give the precise element clicked:
var selector = '#overlay, .postcard a';
$(selector).click(function(e){
var target = $(e.target);
if ( target.is(selector) ) doSomething()
})
EDIT²: this new version shouldn't fire twice: (http://jsfiddle.net/xnu8M/)
$('.postcard a').click(function(e){
var target = $(e.target);
if ( target.is('.postcard a') ) alert('a');
});
$('#overlay').click(function(e){
var target = $(e.target);
if ( target.is('#overlay') ) alert('a');
});
Upvotes: 0
Reputation:
you'll have to break the bubbling.
By one of these examples:
$('#overlay, .postcard a').click(function () {
// call other method
return false;
});
$('#overlay, .postcard a').click(function (e) {
e.preventDefault();
// call other method
});
$('#overlay, .postcard a').click(function (e) {
e.stopPropagation();
// call other method
});
Upvotes: 0
Reputation: 4456
This is due to the event propagation mechanism of Javascript, you can read more at:
http://www.quirksmode.org/js/events_order.html
Javascript: Multiple mouseout events triggered
You can avoid this by disabling the click event at the inner div, like this:
$('.postcard').click( function(evt) { evt.stopPropagation(); } );
Upvotes: 8
Reputation: 51684
If you add a click handler to the overlay, everything inside it will have the handler fired if clicked.
To only make the link clickable you can use the selector like this (without the comma after #overlay
):
$('#overlay .postcard a').click(function(){ doSomething() })
or give the link itself an id:
<div id="overlay">
<div class="postcard">
<p>This is a postcard</p>
<a id="clickMe" href="#">close</a>
</div>
</div>
$('#clickMe').click(function(){ doSomething() })
Upvotes: 0