Quantcast
Channel: Suburban Glory
Viewing all articles
Browse latest Browse all 101

:focus pseudo-class feature detection

$
0
0

javascript logo

I'm not quite sure whose idea the CSS3 :focus pseudo-class class was, but including it in the CSS spec was a minor act of ingenuity.

When you view CSS-only animation then :focus is usually at the centre of the code. For examples, take a look at this login and registration form, content navigator and page transition effect.

As :focus is so wonderful why don't we see more use of it outside of exhibition demos? The answer is two words, Internet Explorer. Versions 8 and below of Microsoft's browser do not support this useful CSS pseudo-class.

Due to this lack of support coders have preferred using JavaScript and its event-driven programming approach to user interaction; but as the demise of the legacy browsers continues and CSS continues to claim greater chunks of the presentation layer, then the appeal of :focus will grow in tandem.

JavaScript object detection

I'm currently working on a version of the well-known lightbox script. I wanted to fully utilise CSS3 animation but have a credible full back for the legacy browsers. As my version was dependent on :focus, the first step was to create a feature detection script so as to then provide a JavaScript event-driven fallback.

It seems though that feature detection for :focus is far from straight forward so I had to resort to a hack. A hack, by my definition, is to use code for a purpose other that what it was intended for. In my example below, I looked for CSS opacity support. Now I know that this property is not supported in IE versions 8 and below and :focus is not supported in versions 8 and below so, therefore, I tested for opacity support because it is easier to script for.

JavaScript purists might throw their legs in the air and have a bit of a fit to this approach, but Internet Explorer is an imperfect browser so solutions to dealing with it are also sometimes imperfect.

The code I created is below. To see it working click through to this jsfiddle page I have created.


var testFocus = (function () {

    var legacy = {
        test: function () {
            return document.getElementsByTagName('body')[0].style.opacity !== undefined;
        }
    };

    var nonLegacy = {
        test: function () {
            return document.getElementsByTagName('body')[0].style.opacity !== undefined;
        }
    };

    if (nonLegacy.test() !== undefined) {
        return nonLegacy;
    } else {
        return legacy;
    }

})();

// Run script like this:
testFocus.test();


Viewing all articles
Browse latest Browse all 101

Trending Articles