How to give the focus with jQuery?

Oct 01, 2009

For the past two years, I have been interesting and working on accessibility issues in all my web development projects. Not because my employer or my clients understand the real importance of offering accessible websites (do they?) but because I believe in an accessible world (and an accessible Internet) for EVERYBODY.

There are lots of articles and resources on the Internet which talk about the theory of the accessibility matter. However, there are not many technical articles which explain how the standards are really implemented or how a web developer has to implement them.

This first article focuses on how to give the… focus on a non-focusable HTML element with jQuery.

It extends (and I hope, completes) the original article written by C. Blouch and published on the Donald F. Evans’s website.

The theory

Giving the focus to a non-focusable HTML element seems to be quite simple. Many articles on the Web were written about it.

To summarize them, you only have to :

  1. Set the tabindex attribute of the selected element to -1
  2. Give the focus to the DOM node with the JavaScript method .focus()

Quite simple, isn’t it?

In fact, after doing few tests with Jaws, it demonstrates that it does not really work that way…

The reality

By default, only a few HTML elements are focusable like anchors or form inputs.
So, in order to give the focus to a non-focusable HTML element correctly, don’t forget to add an important third step:

  1. Set the tabindex attribute of the selected element to -1
  2. Give the focus to the DOM node with the JavaScript method focus()
  3. Use the setTimeout JavaScript function to delay the execution of the focus() function

Without the use of the setTimeout function, Jaws will simply ignore the focus and will not redirect the user to the element where you want to give the focus.

The JavaScript code

$(document).ready(function () {

	$("#addNMoveFocus").click(function(e){

		AddNMoveFocus("ul#nl", "<li><b>A simple b tag inside a li tag</b></li>", "ul li:last b");
		e.preventDefault();

	});

});

function AddNMoveFocus (o1, content, o2){
	AddContent(o1, content);
	MoveFocus(o2);
}

function AddContent(o, content) {
	$(o).append(content);
}

var f; // must be declared as global
function MoveFocus(o){
	$(o).attr("tabindex", "-1");
	f = $(o).get(0);
	setTimeout("f.focus();", 0);
}

The examples

Examples listed below were tested with IE7, Jaws 7.10, Jaws 8, Jaws 9 and Jaws 10

1 Comment

Add your comment

  1. --Nico
    Oct 05 at 18:00

    Reserved

Post a comment

Spam Protection by WP-SpamFree

Main Navigation

I am (not?) a Robot!

Recent Comments

Search

Subscribe and login