Richard
Richard

Reputation: 32909

Check in JS whether a CSS property is supported?

I want to check whether the CSS property pointer-events (see documentation) is supported by the user's browser.

Currently, for example, it's not supported by Opera and I believe some versions of IE.

I'd like to run a check in JavaScript and display appropriate bits of HTML depending on whether or not it's supported.

Is there a better way to do this than checking the user-agent string?

Upvotes: 9

Views: 2670

Answers (3)

ausi
ausi

Reputation: 7413

for non-SVG content this script should work:
https://github.com/ausi/Feature-detection-technique-for-pointer-events

You can also use it without Modernizr:

var pointerEventsSupported = (function(){
    var element = document.createElement('x'),
        documentElement = document.documentElement,
        getComputedStyle = window.getComputedStyle,
        supports;
    if(!('pointerEvents' in element.style)){
        return false;
    }
    element.style.pointerEvents = 'auto';
    element.style.pointerEvents = 'x';
    documentElement.appendChild(element);
    supports = getComputedStyle && 
        getComputedStyle(element, '').pointerEvents === 'auto';
    documentElement.removeChild(element);
    return !!supports;
})();
if(pointerEventsSupported){
    // do something
}

Upvotes: 6

Knu
Knu

Reputation: 15136

I think

if ("pointer-events" in document.body.style)

or

if ("pointerEvents" in document.body.style)

should be adequate in the case of SVG content.

Upvotes: 4

clarkb86
clarkb86

Reputation: 693

The following evaluates to true in both IE 9 and Firefox:

if ('pointerEvents' in document.documentElement.style)

Upvotes: 2

Related Questions