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>
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>
Share
Improve this question
edited Aug 17, 2013 at 15:34
j08691
208k32 gold badges269 silver badges280 bronze badges
asked Aug 17, 2013 at 15:24
user2492270user2492270
2,2856 gold badges43 silver badges56 bronze badges
3 Answers
Reset to default 6$('ul a').on('keydown', function(e){
if(e.which === 13) //enter
e.preventDefault(); //prevent the default behavoir
//(a redirect in this case)
});
http://jsfiddle/Jdf85/
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();
}
} );
Remove the event you do not wish to use.
<style>.disabled { cursor: not-allowed; }</style>
<a class="disabled" href="blah">Click me</a>
<script src="https://ajax.googleapis./ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(".disabled").on("click keydown", function(e){ e.preventDefault() });
</script>