« Back to Index

How to access a specific :after pseudo-element’s styles via JavaScript

View original Gist on GitHub

styles.js

var cache_styles = (function(){
    var cache, len, found;
    
    return function(){
        if (!cache) {
            cache = {};

            // IE9+ and all versions of Firefox/Chrome/Safari
            if (window.getComputedStyle) {
                cache.style = window.getComputedStyle(popup, ':after');
                cache.right = parseInt(cache.style.right);
                cache.top = parseInt(cache.style.top);
                cache.height = parseInt(cache.style.height);
                cache.width = parseInt(cache.style.width);
            }
            // IE8 - needs to loop through stylesheet looking for the relevant Rule to pick up the :after styles from
            else {
                len = document.styleSheets[1].rules.length;

                while (len--) {
                    if (document.styleSheets[1].rules[len].selectorText === '.application-popup:after') {
                        found = document.styleSheets[1].rules[len];
                        break;
                    }
                }

                cache.styles = found.style.cssText.toLowerCase();
                cache.right = parseInt(cache.styles.match(/right: ?([^;]+)/)[1]);
                cache.top = parseInt(cache.styles.match(/top: ?([^;]+)/)[1]);
                cache.height = parseInt(cache.styles.match(/height: ?([^;]+)/)[1]);
                cache.width = parseInt(cache.styles.match(/width: ?([^;]+)/)[1]);
            }
            
            // The following code is *VERY* specific to my use case and so would need to be revisited for others thinking of using this code
            // Currently the values are negative integers so we need to check for that and return positive integer (if need be)
            cache.right = (cache.right < 0) ? Math.abs(cache.right) : cache.right;  // 13
            cache.top = (cache.top < 0) ? Math.abs(cache.top) : cache.top;          // 10
        }
        
        return cache;
    };
}());