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.
Unless im missing something, the most obvious thing to do is add a target to that anchor:
<a data-href="http://www.google.com/" target="blank"> LINK </a>
This is how to do it (try it on your code, stackoverflow blocks new tabs and links)
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.open(href,'','');
});
}
<div>
<a data-href="http://www.google.com/"> LINK </a>
</div>
You can see here, that syntax of window.open is:
var window = window.open(url, windowName, [windowFeatures]);
So to open link in new tab you should use something like:
var myNewTab = window.open(url, '_blank');
It will not work if you window is opened as '_blank'
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.
Why not just use an onclick event handler to redirect the user?
<a href="" onclick="onClick">link</a>
function onClick(e) {
e.preventDefault();
document.location.href='www.google.ca';
}