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 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With