Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to focus element of any kind

I have the following requirements:

On my webpage there are anchor links for navigation (thinks like skip to content etc.). These anchors are supposed to bring the target element into view and focus it. (Focus is important, because else screenreaders don't get positioned correctly. so far my code looks like this:

<a href="#content" class="navbtn">Skip to content</a>
<!-- somewhere else...-->
<div id="content" tabindex="-1">
Lorem ipsum...
</div>
<script>

$(".navbtn").click(function(e) {

    e.preventDefault();

    $("#content").focus();
});

</script>

Please note that I'm aware this is hardcoded and I'll change that in the future, but for test purposes I left it to this.

OK, so what does this do? In this post the method above was said to focus the div element. Visually I cannot judge, but my screenreader won't move to the element (I'm using VoiceOver in Safari on an iPhone). If the target is a button, a link or any other element which has a tabindex by default, it works fine.

Any ideas?

EDIT: I got it to wolk with my braille display when pressing the left mode key. I usually use the right mode key to send a double tap event to the phone, but the right one doesn't work. The left one, however, does. I don't know why, to be honest. Double tap onscreen still doesn't work... Either way, no JavaScript needed.

like image 913
TimB Avatar asked Dec 30 '18 13:12

TimB


People also ask

Does clicking an element focus it?

An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element. Elements with focus are usually highlighted in some way by the browser, for example with a dotted line surrounding the element.

Can multiple elements be focused?

No, you can only focus on one element at a time.

How do you not focus on an element?

In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus and prevent the default interaction. In order to prevent an element from being tabbed to, use tabindex=-1 attribute. Adding tabindex=-1 will make any element focusable, even div elements.


1 Answers

I've just tested the following (with no JavaScript) on an iPhone running iOS12, with VoiceOver in Safari:

<a href="#content">Skip to content</a>
...
<div id="content" tabindex="-1">Target content...</div>

It worked as expected, with focus moving to the target content and VoiceOver announcing "Target content...". Can you describe the steps you're taking when you test in more detail?

like image 147
Léonie Watson Avatar answered Sep 20 '22 00:09

Léonie Watson