Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initiate click on div using tab and enter

I have 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 keyboard tab I can navigate to a link ,press Enter and see alert,but I can't do this for div.

Is it possible initiate click event for div as same as for a tag,without using any other events(keypress)?

JSfiddle

like image 312
vborutenko Avatar asked Dec 02 '14 16:12

vborutenko


1 Answers

I know this is an old post but i thought i might add something.

PeterKA has a nice solution but i would improve it just a bit.
Instead of triggering a new custom event like enter just trigger the click event. This way you don't need to modify existing code and add the new event to every listener you have.
Each element that listens to 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>
like image 166
Sagiv b.g Avatar answered Sep 27 '22 21:09

Sagiv b.g