I have an image embedded within an anchor tag in HTML. The problem is that, when I click the image, I have two tabs that open instead of one.
Problem:
Two tabs are opened, one with the correct link, the other is a blank tab (about:blank
in the address bar).
Relevant sample code:
<a href="javascript:void(0)" onclick="window.open('http://www.google.com');">
<img src="..." />
</a>
What I've tried:
Immediately, I see that the onclick
event is missing return false;
and so I add it. Now the window.open
function is followed by return false;
, but the issue persists.
I tried replacing the javascript:void(0);
with #
in the href
, but the issue remains - only this time instead of a blank tab, I get a new tab with the same content that I had in the tab where the link was clicked.
I also tried replacing the javascript:void(0)
with javascript:;
, but that has the same result.
Additionally, I tried using event.preventDefault();
- again, did not get the desired results.
Workaround:
I've found that if I remove the href
attribute and only have the onclick
one, it works as expected. While this delivers the wanted results, I don't really like it. I also know that using javascript:void(0)
is not considered good practice either, but I don't make all the decisions here.
Points of note:
<img>
element does not contain anything that would affect this.Do you folks have any idea why this may be happening? Any solutions? I'd prefer not to use any 3rd party libraries, although jQuery is possible. Thanks in advance.
If anyone comes across this, the problem was that the <img>
tag had a deeply-enrooted onClick event handler attached to it. So whenever I clicked the <a>
tag, I called two onclick actions - the one from the <a>
tag, and the other from the <img>
one. I solved this problem by calling a new JS function and attaching it to the <a>
tag, passing event as a param, and the function contains the event.stopPropagation();