As we know, when we click on TAB key on keyboard, it allows us to navigate through all active href links present open webpage. Is it possible to read those urls by means of JavaScript?
example:
function checkTabPress(key_val) {
if (event.keyCode == 9) {
// Here read the active selected link.
}
}
You should be able to do this with the keyup event. To be specific, event.target
should point at the selected element and event.target.href
will give you the href-value of that element. See mdn for more information.
The following code is jQuery, but apart from the boilerplate code, the rest is the same in pure javascript. This is a keyup
handler that is bound to every link tag.
$('a').on( 'keyup', function( e ) {
if( e.which == 9 ) {
console.log( e.target.href );
}
} );
jsFiddle: http://jsfiddle.net/4PqUF/
Having following html:
<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>
<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>
<textarea>...</textarea>
You can get to active link with:
// event listener for keyup
function checkTabPress(e) {
"use strict";
// pick passed event or global event object if passed one is empty
e = e || event;
var activeElement;
if (e.keyCode == 9) {
// Here read the active selected link.
activeElement = document.activeElement;
// If HTML element is an anchor <a>
if (activeElement.tagName.toLowerCase() == 'a')
// get it's hyperlink
alert(activeElement.href);
}
}
var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
Here is working example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With