31

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.
    }
}
Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
bharatesh
  • 952
  • 2
  • 11
  • 23
  • 3
    Look at the `document.activeElement` to get the currently focused element (if any, or the `body`). You can check that `.nodeName.toUpperCase() === "a"` and then read its `.href` property – Ian Aug 19 '13 at 14:36
  • Take a look at this question (didn't test it). http://stackoverflow.com/questions/11277989/how-to-get-the-focused-element-with-jquery – Sjors van Dongen Aug 19 '13 at 14:43
  • 2
    @Ian Did you mean `.toLowerCase()`? – rink.attendant.6 Aug 19 '13 at 15:01
  • 1
    @rink.attendant.6 Well crap, of course I did. Haha thanks, didn't even realize that. With whatever method, I definitely meant to match the case obviously – Ian Aug 19 '13 at 15:20
  • Javascript Example to Handle TAB and TAB+SHIFT in a specified element to Loop in http://www.freakyjolly.com/navigate-form-field-link-elements-using-tab-and-shifttab-keys-in-webpage/ – Code Spy Jul 24 '18 at 04:54

9 Answers9

15

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/

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
  • This will point to the selected element at the time the tab key is pressed, not the new element that has been focused. – zzzzBov Aug 19 '13 at 15:01
  • 1
    keydown will be fired before whatever the key does (and you can cancel whatever it does then), as far as I am aware (and as far as I can test in IE8) keyup will point to the new element, as the keyup is fired after whatever that key would do. – Sumurai8 Aug 19 '13 at 15:04
  • I didn't know that you could bind to the `a` element and still have it trigger if the previously focused element wasn't an `a`. +1, despite the use of jQuery. – rink.attendant.6 Aug 19 '13 at 15:15
14

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.

uKolka
  • 36,422
  • 4
  • 33
  • 44
3

Only one suggestion instead of 9 you can use KeyCodes.TAB.

Deepak
  • 614
  • 1
  • 7
  • 20
Panky031
  • 425
  • 1
  • 5
  • 14
1

Given this piece of HTML code:

<a href='https://facebook.com/'>Facebook</a>
<a href='https://google.ca/'>Google</a>
<input type='text' placeholder='an input box'>

We can use this JavaScript:

function checkTabPress(e) {
    'use strict';
    var ele = document.activeElement;

    if (e.keyCode === 9 && ele.nodeName.toLowerCase() === 'a') {
        console.log(ele.href);
    }
}

document.addEventListener('keyup', function (e) {
    checkTabPress(e);
}, false);

I have bound an event listener to the document element for the keyUp event, which triggers a function to check if the Tab key was pressed (or technically, released).

The function checks the currently focused element and whether the NodeName is a. If so, it enters the if block and, in my case, writes the value of the href property to the JavaScript console.

Here's a jsFiddle

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
1

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Niravdas
  • 371
  • 2
  • 19
0

Use TAB & TAB+SHIFT in a Specified container or element

Source

we will handle TAB & TAB+SHIFT key listeners first

        $(document).ready(function() {
            lastIndex = 0;
            $(document).keydown(function(e) {
                if (e.keyCode == 9) var thisTab = $(":focus").attr("tabindex");
                if (e.keyCode == 9) {
                    if (e.shiftKey) {
                        //Focus previous input
                        if (thisTab == startIndex) {
                            $("." + tabLimitInID).find('[tabindex=' + lastIndex + ']').focus();
                            return false;
                        }
                    } else {
                        if (thisTab == lastIndex) {
                            $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
                            return false;
                        }
                    }
                }
            });
            var setTabindexLimit = function(x, fancyID) {
                console.log(x);
                startIndex = 1;
                lastIndex = x;
                tabLimitInID = fancyID;
                $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
            }
            /*Taking last tabindex=10 */
            setTabindexLimit(10, "limitTablJolly");
        });

In HTML define tabindex

        <div class="limitTablJolly">
            <a tabindex=1>link</a>    
             <a tabindex=2>link</a>    
             <a tabindex=3>link</a>    
             <a tabindex=4>link</a>    
             <a tabindex=5>link</a>    
             <a tabindex=6>link</a>    
             <a tabindex=7>link</a>    
             <a tabindex=8>link</a>    
             <a tabindex=9>link</a>    
             <a tabindex=10>link</a>   
        </div>
Code Spy
  • 9,626
  • 4
  • 66
  • 46
0

You should be able to do this with the keydown 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 keydown handler that is bound to every link tag.

$('a').on( 'keydown ', function( e ) {
if( e.which == 9 ) {
    console.log( e.target.href );
}});
Saif
  • 9
  • 4
0

event.keyCode has been deprecated.

Use event.key instead.

Here are the values you can use to assert against event.key: https://www.w3.org/TR/uievents-key/#named-key-attribute-values

Use this JavaScript solution:

  function keyPress(event) {
    if (event.key === "Tab") {
       // ...
    }
  }
Robert Rendell
  • 1,658
  • 15
  • 18
-10

You need to use Regular Expression For Website URL it is

var urlPattern = /(http|ftp|https)://[\w-]+(.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/

Use this Expression as in example

var regex = new RegExp(urlPattern ); var t = 'www.google.com';
var res = t.match(regex /g);

For You have to pass your web page as string to this javascript in variable t and get array