g-ulrich
g-ulrich

Reputation: 51

How to use JavaScript or jQuery to select an anchor tag using the enter key

I'm stuck trying to select an anchor tag inside of an unordered list using the keyboard arrow keys and hitting the enter key. The arrow keys will highlight the link, triggering the native browser behavior text-decoration:underline, but using the following produces nothing.

$('body').on('keydown', function(e) {
   var code = (e.keyCode ? e.keyCode : e.which);
   if(code == 13) {
      console.log($('body').find('a:active, a:focus'));
   }
})

Upvotes: 0

Views: 43

Answers (1)

Matteo Gomez
Matteo Gomez

Reputation: 1

This should help

$('body').on('keydown', function(e) {
   var code = (e.keyCode ? e.keyCode : e.which);
   if(code == 13) {
      var focusedLink = $('a:focus');
      console.log(focusedLink);
      focusedLink[0].click();
   }
});

Upvotes: -1

Related Questions