Skip to content

Instantly share code, notes, and snippets.

@kristofferh
Created May 17, 2011 22:22
Show Gist options
  • Save kristofferh/977550 to your computer and use it in GitHub Desktop.
Save kristofferh/977550 to your computer and use it in GitHub Desktop.
Check if :before pseudo selector is supported
/**
* Check if :before pseudo selector is supported. This can be useful for sprites.
* usage: if(!pseudoTest()) {
* // do polyfill
* }
*/
var pseudoTest = (function() {
var cache;
return function() {
if(cache === undefined) {
var span = document.createElement('span'),
style = document.createElement('style');
document.body.appendChild(style);
document.body.appendChild(span);
span.className = 'pseudo-test';
addCssRule('.pseudo-test', 'left: -99999px;position: absolute;top: -99999px;');
addCssRule('.pseudo-test:before', 'content: "";display: block;width: 1px;');
if(span.offsetWidth !== 1) {
// browser does not support :before pseudo element
cache = false;
} else {
cache = true;
}
// cleanup
document.body.removeChild(style);
document.body.removeChild(span);
}
return cache;
}
})();
var addCssRule = function(selector, rules) {
// dynamically add styles
var length = 0,
sheet;
sheet = document.styleSheets[document.styleSheets.length-1]; // get the last stylesheet
if (sheet.cssRules) {
length = sheet.cssRules.length;
} else if (sheet.rules) {
// IE
length = sheet.rules.length;
} else {
// can't, fail quietly
}
// try to insert a new rule, the 'standard way' first
if (sheet.insertRule) {
sheet.insertRule(selector + ' {' + rules + '}', length);
} else if (sheet.addRule) {
// IE
sheet.addRule(selector, rules, length);
} else {
// fail quietly
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment