jQuery: set focus on all elements

jQuery: set focus on all elements

Setting focus on all elements with jQuery involves the use of the tabindex attribute. Always bear in mind what this solution implies for accessibility.

Setting focus on all elements with jQuery is pretty easy. However, the following solution makes use of the tabindex attribute, so if your site really wants to be accessible, you should not use this solution. Playing with the tabbing order is always a risk, because assistive technologies always run into troubles when you alter the tabbing order. Said that, let's see the details.

Simply set the tabindex attribute to -1 and then use the normal focus and blur events:

$('#test').attr('tabindex', '-1');

$('#test').bind('focus', function() {
    $(this).addClass('focus');
});

$('#test').bind('blur', function() {
    $(this).removeClass('focus');
});

That's all. Always bear in mind accessibility, though.

Demo

Live demo