Reputation: 43
I'm building a Screen Reader and I'm wanting to navigate through HTML elements on the page using Tab and Shift+Tab presses.
So far, I've got the following code, which works fine:
$('a, input, button').keyup(function(e) {
// code
});
However, the problem I have is the above code will only work for a tags, inputs, and buttons. If I want to add code for a span, or a summary tag, I would have to change the code to:
$('a, input, button, span, summary').keyup(function(e) {
// code
});
I was wondering if its possible to re-write this so that it handles every HTML element. I tried something like:
$('*').keyup(function(e) {
// code
});
But that didn't work. Any help would be appreciated!
Upvotes: 1
Views: 788
Reputation: 43
Thanks to @Reflective for their contribution. Using parts of their answer, I've formed the below, which works:
$(document).keyup(function(e) {
if (e.key == 'Tab') {
console.log($(e.target).text());
}
});
You can then use the $(e.target)
to access what you want from the current element.
Upvotes: 0
Reputation: 3917
Please first read about event propagation. Your event (if not stopped by e.stopPropagation()
or e.stopImmediatePropagation()
) will be spread to all parents, so it's absolutely enough to do the following.
$(document).keyup(function(e) {
// code
});
Of course you can catch the event on any other level if you need to handle the event on some area but not on whole document. Here's an example of that case when just A1 and A2 buttons wrapped in .containerA
div will be handled.
$(function(){
$('.containerA').keyup(function(e) {
if (e.key == 'Tab') {
console.log($(e.target).text());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="containerA">
<button>A1</button>
<button>A2</button>
</div>
<div class="containerB">
<button>B1</button>
<button>B2</button>
</div>
Talking about the tabbing, you probably need to capture on focus event, but that's not clear so I will stop with this immediate answer of your question.
Upvotes: 1