Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript for handling Tab Key press

Tags:

javascript

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.
    }
}
like image 781
bharatesh Avatar asked Aug 31 '25 03:08

bharatesh


2 Answers

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/

like image 144
Sumurai8 Avatar answered Sep 02 '25 17:09

Sumurai8


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.

like image 25
uKolka Avatar answered Sep 02 '25 16:09

uKolka