admin管理员组

文章数量:1277901

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

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

Share Improve this question asked Dec 2, 2014 at 16:29 vborutenkovborutenko 4,4435 gold badges32 silver badges50 bronze badges 3
  • Not all browsers support tabindex=0 for divs - it is not allowed in w3c remondation, keep that in mind! w3/TR/html401/interact/forms.html#adef-tabindex – Martin Lantzsch Commented Dec 2, 2014 at 16:33
  • As Martin said. Everything need to be wrap in a link tag to be access with tab. It's a convention in accessibility. – Mathieu Labrie Parent Commented Dec 2, 2014 at 16:35
  • HTML4 does not allow tabindex on div -- w3/TR/html401/interact/forms.html#adef-tabindex -- but HTML5 does allow it -- dev.w3/html5/spec-author-view/…. – Luke Commented Apr 17, 2019 at 17:47
Add a ment  | 

2 Answers 2

Reset to default 5

You can create a custom event like this:

$("div").on("click enter",function(){
    alert("div click")

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

DEMO

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./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>

本文标签: javascriptInitiate click on div using tab and enterStack Overflow