Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent <a> link from opening when pressing the ENTER key

I have a list, in which each element contains a link. By default, when the list element has "focus" and the I hit the ENTER key, the browser automatically redirects to the link. Is there a way to prevent this behavior?

So simply, I guess my question is how to prevent a link from opening when the user hits ENTER on "focus()"

HOWEVER, I still want to keep the link opening behavior on mouse CLICK event!!

<ul>
    <li> <a href="SOMELINK1">LINK1</a> </li>
    <li> <a href="SOMELINK2">LINK2</a> </li>
<ul>
like image 621
user2492270 Avatar asked Sep 19 '25 06:09

user2492270


2 Answers

$('ul a').on('keydown', function(e){

     if(e.which === 13) //enter
         e.preventDefault(); //prevent the default behavoir
                             //(a redirect in this case)
});

http://jsfiddle.net/Jdf85/

like image 172
Johan Avatar answered Sep 22 '25 06:09

Johan


The onclick-event doesn't make a difference between the 'mouse' click and the 'enter' click. You can detect clicking with 'enter' with onkeydown though. Please note that you make it impossible/more difficult for people with disabilities to browse your site if you remove this functionality.

$('a').on( 'keydown', function( e ) {
    if( e.which == 13 ) {
      e.preventDefault();
    }
} );
like image 27
Sumurai8 Avatar answered Sep 22 '25 08:09

Sumurai8