views:

36

answers:

4

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"&gt;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?

A: 

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

Peter Kruithof
@Peter Kruithof, this looks promising but how would I do that with the onclick? Would it be ..... *onclick="if (!e) var e = window.event;e.cancelBubble = true;if (e.stopPropagation) e.stopPropagation();window.open('http://example.com')"*
TeddyR
The code I posted in the comment directly above doesn't work. Any ideas?
TeddyR
Just to be clear, I tried the following code and it didn't work:*<div onclick="if (!e) var e = window.event;e.cancelBubble = true;if (e.stopPropagation) e.stopPropagation();window.open('example.com')">....</div>*
TeddyR
@TeddyR you can put a function reference inside your onclick attribute (`onclick="myFunc"`) and use that function to stop the event. But Rob's suggestion is much easier (a bit dirtier, depending on your opinion on unobtrusive javascript, but then again, so is an onclick attribute).
Peter Kruithof
+1  A: 

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

div a {
    display: block;
}
Wai Wong
Hmmm.. this would only work if the div only has a link inside of it. Didnt check the entire code properly
Wai Wong
This doesn't work.
TeddyR
A: 

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.

Dominique
@Dominique, I believe that is what Peter Kruithof is suggesting but I have not been able to get the code to work.
TeddyR
+1  A: 

The simple solution:

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