JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.
August 21, 2010

Testing for Input Focus

Though part of the HTML5 Specification, the activeElement attribute is now supported by all major browsers and offers the ability to determine whether an element currently has the user’s focus very easily.

Previously making the determination for which input element currently had focus was done using multiple event handlers applied to all input elements. (Note: The selector below does not include form inputs not based on the <input> tag such as a <select> list)

var current_focus; // Maintains a reference to the currently-focused input
$(document.body).getElements('input').each(function(f){
    $(f).addEvents({
        'focus': function(){
            current_focus = $(this);
        },
        'blur': function(){
            current_focus = false;
        }
    });
});

//... and later

if (current_focus == $('element-in-question')) {
    // The element in question currently has the user's focus
}

Now that most major browsers support activeElement, the test for an input having focus can be done without any event handlers.

if ($(document.activeElement) == $('element-in-question')) {
    // The element in question currently has the user's focus
}

Ideally your application’s code will include the old version as a fallback along with the above solution to accommodate all browsers.

Tags: Mootools javascript tips code mdc