TeddyR
TeddyR

Reputation: 1213

HTML: Browser opens 2 tabs when someone clicks a link on my web site?

I have the following HTML code:

<div onclick="window.open('http://example.com')" >
<p>1234 Main St, New York, NY</p>
<p>Price: $200,000/p>
<p>4 Beds / 3 Baths</p>
<p>2000 sqft</p>
<a href="http://example.com">More Info</a>
</div>

If the person hovers over the part of the DIV that is not the hyperlink, it only opens one window.

If the person clicks on the hyperlink within the DIV, it opens 2 windows (one for the DIV and one for the hyperlink).

Is there any way around this 2x opening window scenario?

Upvotes: 0

Views: 4541

Answers (5)

Priyank Shrivastava
Priyank Shrivastava

Reputation: 11

I came across the same issue and please don`t laugh on my silly mistake. But two tabs was opening because i am having a link and having target='_blank' and also calling a function too on the same like:

<pre>
$('#foo').on('click',function(){
// some code
window.open("https://www.google.com","_blank");
});

where also i have added the target as _blank. i removed the target attribute from the anchor and it works fine for me. Hope you are not doing same.

Upvotes: 0

Rob
Rob

Reputation: 8195

The simple solution:

<a href="http://example.com" onclick="return false;">More Info</a>

Upvotes: 3

Dominique
Dominique

Reputation: 908

You could use the same function in both the DIV and the A HREF, and manage the opening inside that function to call the window only once, that will work.

Edit : If you care at least a little about Search Engine Optimization you should not use that caption for the link, but more something mentionning the content of the next page like "House details" or better depending of the context/look of the page.

Upvotes: 0

Wai Wong
Wai Wong

Reputation: 2843

You could make the div clickable by making the link into a block element with css

div a {
    display: block;
}

Upvotes: 1

Peter Kruithof
Peter Kruithof

Reputation: 10764

That's because the click event bubbles up. It initiates when you click the anchor element, than bubbles up to the div, and executes that too.

You need to capture the click event inside the div (using a function), and then call the event's stopPropagation method to stop it from bubbling up.

More info about event bubbling here: http://www.quirksmode.org/js/events_order.html

Upvotes: 0

Related Questions