Currently, Internet Explorer doesn’t support ‘:focus‘ within CSS selectors, a dynamic pseudo-class implemented in CSS2. The Anchor and most form elements (input, textarea etc.) support this psuedo class. It’s normally used to make it obvious to the user where ‘focus’ currently is. This can be especially useful for users who browse without a mouse (just using a keyboard).

It’s easy enough to fix with JavaScript; you can just apply the styles on the ‘focus’ and ‘blur’ events. The problem with this is that you’ll also be affecting browsers that already have support for ‘:focus’. So you need a reliable way (no browser sniffing) of determining whether or not it’s supported. Also, manually adding these event handlers where needed is a bit of a pain… something we could certainly do without.

‘pseudoFocus’ is a jQuery plugin that fixes the ‘focus’ pseudo class in all browsers that don’t support it. It doesn’t use browser sniffing to determine support, but instead performs a check to determine whether the browser in question supports the specific feature:

var focusIsSupported = (function(){
    // Create an anchor + some styles including ':focus'.
    // Focus the anchor, test if style was applied,
    // if it was then we know ':focus' is supported.
    var ud = 't' + +new Date(),
        anchor = $('<a id="' + ud + '" href="#"/>').css({top:'-999px',position:'absolute'}).appendTo('body'),
        style = $('<style>#'+ud+'{font-size:10px;}#'+ud+':focus{font-size:1px !important;}</style>').appendTo('head'),
        supported = anchor.focus().css('fontSize') !== '10px';
    return supported;

Once it has performed the check it will then run through all the StyleSheets looking for selectors with the ‘focus’ psuedo class (or ‘:unknown’ in IE6) and then automatically attaches the ‘focus’ and ‘blur’ handlers to whatever elements are targeted by each of those selectors.

Note that this will only work if your rules are defined in an external StyleSheet, the plugin won’t check for styles within <style/> tags.

A quick demo is available here: /demos/plugins/jQuery/pseudofocus/, and you can download the entire plugin here: /demos/plugins/jQuery/pseudofocus/pseudofocus.js

Another note: If you need to support more than just anchors, buttons, inputs and textareas then you can add to the isAcceptable variable within the plugin. It’s a comma separated list that defines “focusable” elements. The reason for this list is to ensure that all selectors containing ‘:focus’ work, even including the following:

#nav a:focus span.whatever {}
#nav a:focus {}
#go-button:focus img {}

Be aware that you can’t add any element to this list and expect it to work; the list is only there to provide a primitive check – elements that have no ‘focus’/’blur’ events will not be effected.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!