Reputation: 33
I have a page with multiples divs like this
<div class="bigbox">
<a href="http://www.somestuff.com">some stuff</a>
more elements
</div>
I'm trying to make each div open the link inside it when clicked and tried like that:
$('div.bigbox').each(function(){
$(this).click(function(){
window.open($(this).find('a').attr("href"));
})})
But when clicking on the actual link, it will open it twice. Any suggestion to not have .click trigger when clicking on the link inside my div?
Upvotes: 3
Views: 1394
Reputation: 8980
I believe you're pretty close with your code. Try this:
$('div.bigbox').click(function()
{
window.open($(this).find('a').attr('href'));
return false;
});
The return false
should keep it from opening more than once, so give that a try and see how it works.
Upvotes: 1
Reputation: 2924
you want your handler to be called when the div is clicked, but not when the link inside the div is called?
how about adding
$('div.bigbox').each(function( event ){
$(this).click(function(){
// only perform the action if the div itself was clicked
if ( event.target == this ) {
window.open($(this).find('a').attr("href"));
}
})
})
Upvotes: 1
Reputation: 2094
In my opinion, you'd be better off just doing this:
<a href="http://www.somestuff.com">
<div class="bigbox">
More elements
</div>
</a>
If you'd rather use javascript, you can always just do this:
$('div.bigbox').click(function(e)
{
window.open($(this).find('a').attr('href'));
e.preventDefault();
});
Upvotes: 0
Reputation: 111
You could do something like:
$('div.bigbox').find('a').click(function(e) {
e.preventDefault();
});
That would prevent any tags iniside .bigbox divs from firing their click events.
Upvotes: 2
Reputation:
By open twice, I assume you meant that the link is followed in the original window as well as the new window.
Just add return false
, or e.preventDefault()
to stop this.
$('div.bigbox').click(function(e){
e.preventDefault()
window.open($(this).find('a').attr("href"));
});
Upvotes: 2