How can I ‘do something’ with jQuery when entering a div using the keyboard tab key? For example, when a user navigates using the keyboard tab button, and they enter the ‘Inside’ div in the example below, the console log doesn’t fire until the tab button is pressed a second time:
$('.inside').on('keydown', function(e) {
if (e.keyCode === 9) {
console.log('Inside');
}
});
.inside {
border: 1px solid black;
margin: 10px;
min-height: 300px;
padding: 20px;
}
.outside {
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="outside text-center">
<a href="">Outside Link 1</a>
<a href="">Outside Link 2</a>
<a href="">Outside Link 3</a>
<a href="">Outside Link 4</a>
</div>
<div class="inside text-center">
<a href="">Inside Link 1</a>
<a href="">Inside Link 2</a>
<a href="">Inside Link 3</a>
<a href="">Inside Link 4</a>
</div>
</div>
3
Answers
Listen for the
focus
event on the DIV’s links and if the previous focused element is outside of the DIV, react to the event. Works with any TAB navigation direction and the mouse also.Try using:
Basically, when using ‘keydown’, the listener that triggers your function waits for the tab button to be pressed after the focus entered the .inside div. So, if you need the function to be triggered as soon as the focus moves to .inside div, then you can just check if tab button goes ‘up’ inside the .inside div
UPD: if you need it to be triggered only for the first link, then something like this should work (the code a bit messy but it does what you need)
You should use the
keyup
event instead.Be aware that
keyCode
is deprecated. It is better to usekey
instead.In the example below,
event.currentTarget
is always thediv.inside
element. So we can always query down to the:first-child
and compare it to theevent.target
.