Reputation: 64
I am trying to get the href of the currently hovered link using JavaScript in order to open that link in a new tab.
I could fetch the href of the current page using:
var myLink = window.location.href;
and then call:
window.open(myLink);
But I would like to call some JavaScript function that returns the link of the element under the mouse (Just like how Right-Clicking and then choosing Copy Link Location works in Chromium or Firefox browsers).
EDIT: Well I tried this:
(function(){
var list = document.querySelectorAll( 'a' );
var myString = "myString_Default_Value";
for ( var i = 0; i < list.length; i ++)
list.item(i).onmouseover = function() { myString = this.href; };
return myString;
})();
Reason why I did this is because I am passing the outer anonymous method as a string from my .NET application (don't worry, I escaped the double quotes in my code) and then getting a callback with the JS result (in this case it's a string result).
Unfortunately in my application I keep getting the default value of myString.
Any ideas?
Upvotes: 1
Views: 4103
Reputation: 174957
If all you want is opening some links in a new tab, just add target="_blank"
(or target="_new"
) to any link you want in a new tab.
//[].forEach.call allows calling .forEach on array-like objects.
[].forEach.call(document.querySelectorAll('a'), function(link) {
if (shouldBeInNewTab(link.href)) { link.target = "_blank"; }
});
What you normally do, is add event listeners to all links on the page, like so:
[].forEach.call(document.querySelectorAll('a'), function(link) {
link.addEventListener('mouseover', function(event) {
console.log(this.href); // `this` being the element triggering the event.
});
});
But this has disadvantages:
So we can solve this with event delegation, basically, I add a listener on a common ancestor (in this case, document
), and filter for items on the inside.
document.addEventListener('mouseover', function(event) {
var hoveredEl = event.target; // The actual element which was hovered.
if (hoveredEl.tagName !== 'A') { return; } // Ignore non links
console.log(hoveredEl.href); // Do what we want here!
});
Upvotes: 2
Reputation: 439
Here we go:
HTML:
<a id="myLink" href="http://www.google.es">Click here</a>
JS:
document.querySelector("#myLink").onmouseover = function(){
window.open(this);
}
EDIT: OK, this doesn't answer the question, anyway I'm keeping it here by OP's petition.
Upvotes: 0
Reputation: 9093
You can do it using jQuery like this:
$('a').on('mouseover', function(){ console.log( this.href ) } )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
</ul>
And the JS without jQuery:
var list = document.querySelectorAll( "a" );
for ( var i = 0; i < list.length; i ++)
list.item(i).onmouseover = function() { console.log(this.href ) };
Upvotes: 1