3

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?

5 Answers 5

2

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"));
});
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

1 Comment

Tried this one first and it indeed works. I had only tried adding return false to the a element to try to block it when javascript is enabled, but that was totally blocking the link.
1

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"));
    }
  })
})

Comments

0

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.