Handle tab press for any HTML element in jQuery/JavaScript - javascript

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!

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.

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.

Related

Closing css dropdown using jquery

Sorry for the vague project title but I'm not having a great idea about how to explain this.
So, let's dive in to it. I was in need of a dropdown list with multiple select options to select recipients from.
I've started my search on Codepen and came across this: https://codepen.io/MaartenTe/pen/mXYLXj
I've forked it so I could tweak it myself. The snippets works perfect. The only thing missing is the ability of closing the dropdownlist when clicking outside of it.
So I started to approach it using javascript. So far I got following code:
$(document).click(function(e) {
var target = e.target; //target div recorded
if (!$(target).is('.multi-select ') ) {
$('.multi-select-options span').css('display', 'none');
$('.multi-select-options label').css('display', 'none');
}
});
Although this isn't working the way I want, I think it's the right approach?
Looking at how that works, its a checkbox that causes the toggle so you need to clear that when you click out the box.
$('.multi-select').on('click', function(e){
e.stopPropagation()
});
$(window).on('click', function(e) {
$('#toggle-open').attr({checked: false})
});
The stopPropagation will stop the window click even firing. https://codepen.io/anon/pen/rdwrya?editors=1111
What works in the given codepen:
var toggle = document.getElementById('toggle-open');
document.addEventListener('click', function(event) {
if (['INPUT', 'LABEL', 'SPAN'].indexOf(event.target.nodeName) + 1) return;
if (toggle.checked) toggle.checked = false;
});
Just handle click, exclude the relevant elements and uncheck if needed.

How to use javascript to select (a) child(ren) element(s) of a hovered element?

assuming I have a (very large) div tag and inside the div tag I have a (normal size) button, now I want to be able to create a shortcut that if a user is hovering over the div tag, they can press return key to click the button.
$(window).keypress(function(e){
if (e.keyCode == xxx) {
$('div').hover(function(){
$('this button').click();
});
}
});
This is how I imagine it might look like in jQuery (didn't work obviously). I am open to suggestions. jQuery solutions are fine, plain javascript solutions are even better.
It's actually pretty easy.
$(window).keypress(function(e){
if (e.keyCode == xxx) {
$('div:hover button').click();
}
});
Don't use .hover() or .on('hover') because they are simply not selectors.
You can use .is(":hover") within your keypress handler to determine if the proper div is being hovered:
$(window).keypress(function(){
if($("#target").is(":hover")){
alert("pressed!");
}
});
http://jsfiddle.net/y7joukzw/2/
(NOTE: Make sure you click within the "result" frame to ensure it is the active frame when testing the jsfiddle)
Rather than checking for hover on every keypress, you're better off reversing the order of event checking so that you only incur the keypress overhead while the user is hovering. Something like:
function checkKeypress(e) {
// Check keypress and perhaps do something
}
$('div').hover(
function(){
$(window).keypress(checkKeypress);
},
function() {
$(window).off('keypress', checkKeypress);
}
);

How do I create an exception for a link my "active" scroll menu in jQuery?

I've got this code that goes through all my internal hrefs but I can't see to be able to figure out how to create an exception for one of the links that links to the div #section1. I need some kind of if statement surrounding the section.addClass("active"); line but I don't know which conditions to use to achieve this. Can you help?
Code: http://jsfiddle.net/vD3vP/
if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
//remove all selected elements
sections.removeClass("active");
//add current selected element.
section.addClass("active");
}
Like this:
$('a[href^="#"]:not(#exception)').click(function (event) {
//do stuff
});
Fiddle: http://jsfiddle.net/KyleMuir/vD3vP/1/
EDIT: You can determine whether or not it is the exception like this:
//Smooth scroll when user click link that starts with #
$('a[href^="#"]').click(function (event) {
if (!$(this).is('#exception')) {
alert('Hi');
}
//prevent the browser from jumping down to section.
event.preventDefault();
});
Fiddle: http://jsfiddle.net/KyleMuir/vD3vP/2/
Unless I misunderstood your question, you might add
$('a[href^="#section1"]').removeClass("active");
after section.addClass("active"); in the for loop inside checkSectionSelected().
You can do even better if you don't update the DOM tree unnecessarily using:
section.not('[href^="#section1"]').addClass("active");
Test here: http://jsfiddle.net/bcH3S/2/
Andrei

Jquery - hide on click anywhere on document

I have a div that hides whenever you click outside of it but I'm having some trouble getting certain links inside the div to work (and not hide the div).
$(document).click(function() {
fav.hide();
});
theDiv.click(function(e) {
e.stopPropagation();
});
That is what I have for the whole clicking outside and closing event. Heres the thing: I have two types of links in my div, one regular link and another which is a javascript one. The regular one redirects OK but the javascript one doesn't do anything.
Could somebody help me out? Thanks.
EDIT:
Here are the bits of my code that might help out
var fav = $('#favorites');
// Open & close button
$('#favorites_a').click(function(e) {
e.stopPropagation();
e.preventDefault();
fav.toggle();
});
$('a.c',fav).live('click', function(e) {
alert('hey');
});
$(document).click(function() {
fav.hide();
});
fav.click(function(e) {
e.stopPropagation();
});
HTML (built after page load):
<div id="favorites">
<div class="wrap">
<ul><li>AB</li></ul>
</div>
</div>
This could be a problem with the live() click event handler. When you use live the event handler is actually attached to the document. So the event needs to bubble up to the document, but your click event handler on fav prevents bubbling up.
It works with delegate though:
fav.delegate('a.c', 'click', function(e) {
alert('hey');
});
Here, the event handler is added to fav.
DEMO
I think your code for fav is preventing the 'B' link from working. Instead of .live(), try:
$('a.c').click(function() { ... });
instead.

Closing form on "blur" -- Is there a better way?

So, i'm trying to close a form on blur, e.g. Facebook comments. The issue is, I had a:
$(window).click(function(){ $('.comment_form').hide(); });
$('.comment_form').click(function(){ return false; });
Which worked fine, however, by adding that return false, it cancels out the submit button when clicked when i actually went to make it live.
I thought this would work logically instead:
$('*:not(.comment_form,.comment_form *)').click(function(eve)
{
$('.comment_form').hide();
});
But, unfortunatly, it doesn't and i assume it's because when i click on, let's say, .comment_form i actually am clicking on body, div, div... etc so it actually hides it multiple times.
My work around was finally
$('*').click(function(eve)
{
if(!$(eve.target).is('.comment_form,.comment_form *'))
{
$('.comment_form').hide();
}
});
However, i'm not so sure i like this and this is why im asking. This is going to fire this click event every single click.
Does anyone have any suggestions?
Your solution is on the right track, but it might be saner to attach the event to document, instead of all elements (*):
$(document).click(function(eve) {
if (!$(eve.target).is('.comment_form, .comment_form *')) {
$('.comment_form').hide();
}
});

Categories