link
div
...">

Initiate a click on a div using a tab and enter

I have an a and div element

<a href="javascript:void(0)">link</a> <div tabindex="0">div</div> 

And click event handlers

 $("a").on("click",function(){ alert(" a click") }); $("div").on("click",function(){ alert("div click") }); 

Using the keyboard tab, I can go to the link, press Enter and see a warning, but I can not do this for a div.

Is it possible to trigger a click event for a div in the same way as for a tag, without using any other events (keystroke)?

Jsfiddle

+6
source share
2 answers

You can create a custom event as follows:

 $("div").on("click enter",function(){ alert("div click") }) .on('keypress', function(e) { if(e.which === 13) { $(this).trigger( 'enter' ); } }); 

Demo

+3
source

I know this is an old post, but I thought I could add something.

PeterKA has a good solution, but I would improve it a bit.
Instead of triggering a new custom event, such as enter , the click event simply fires. Thus, you do not need to modify the existing code and add a new event to each listener that you have.
Each element that listens for click will be triggered.

 $('.btn').on("click",function(){ alert("div click") }) // at a centrelized spot in your app $('.btn').on('keypress', function(e) { if(e.which === 13) { $(this).trigger('click'); } }); $(document).ready(function(){ $('#firstDiv').focus(); // just focusing the first div }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="firstDiv" class="btn" tabindex="0">div</div> <div class="btn" tabindex="0">div</div> <div class="btn" tabindex="0">div</div> 
+1
source

Source: https://habr.com/ru/post/979000/


All Articles