jQuery: how to give focus to a label element

jQuery: how to give focus to a label element

How to add a special CSS class to a label element with jQuery when its related input element gets focus.

The label element cannot receive focus directly but only by means of its related input element. We can mimic this behavior with jQuery by adding or removing a special CSS class on the input element linked to the label element through the for attribute.

The jQuery code is rather simple:


$('form :input').focus(function() {
    $('label[for="' + this.id + '"]').addClass('labelfocus');
}).blur(function() {
    $('label[for="' + this.id + '"]').removeClass('labelfocus');
});​

Simply put, our special class is added when an input element, whose ID attribute is equal to the value of the label's for attribute, gets focus. When such an element loses focus, the CSS class is removed.

You can see the demo on this page.