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
ondiv
-- 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
2 Answers
Reset to default 5You 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
版权声明:本文标题:javascript - Initiate click on div using tab and enter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741222735a2361276.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论