I am using the following javascript (provided by m59 in this previous answer) to hide the destination of a link which usually shows up at the bottom of the browser window when hovering over a link:
<div>
<a data-href="http://www.google.com/"> LINK </a>
<script type="text/javascript">
var anchors = document.querySelectorAll('a[data-href]');
for (var i=0; i<anchors.length; ++i) {
var anchor = anchors[i];
var href = anchor.getAttribute('data-href');
anchor.addEventListener('click', function() {
window.location = href;
});
}
</script>
</div>
This works perfectly fine, but I would like the link to open in a new tab as well. How do I have to change the script in order to do so?
I tried using window.open('href','_blank');
instead of window.location = href;
which did not work.
Why not just use an onclick event handler to redirect the user?
This is how to do it (try it on your code, stackoverflow blocks new tabs and links)
Unless im missing something, the most obvious thing to do is add a target to that anchor:
Did you try
window.open(href)
?i.e. In your example,
href
is a string (there are single quotes around it) as opposed to a variable.You can see here, that syntax of window.open is:
So to open link in new tab you should use something like:
It will not work if you window is opened as '_blank'