Skip to content Skip to sidebar Skip to footer

Set Style With :hover Javascript

I understand that the following method is great for setting CSS styles because of browser compatibility. element.style.cssText = 'color:red;'; What I can't do is use cssText to ap

Solution 1:

You can do it with some Voodoo magic:

var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
var declarations = document.createTextNode('selector:pseudo { property: value }');

style.type = 'text/css';

if (style.styleSheet) {
  style.styleSheet.cssText = declarations.nodeValue;
} else {
  style.appendChild(declarations);
}

head.appendChild(style);

Not exactly what you needed, but you can tweak it and make a fancy function out of it if you want.

Solution 2:

You could always add an individual style rule to an existing style sheet, instead of creating a new style element. Something along the lines of:

functionaddStyle() {
    var style = document.styleSheets[0];        //select style sheet (0==first)var styleSel = ".class:hover";              //define selectorvar styleDec = "color: red;";             //define declarationif(style.insertRule) {        //for modern, DOM-compliant browsers

        style.insertRule(styleSel+'{'+styleDec+'}', style.cssRules.length);
        //I chose to do it this way to more easily support the addRule method, but//know that insertRule only needs two parameters, full style rule//(selector+prop/value declarations), and index to insert rule at//                  styleSheets[0].insertRule(rule, index);

    }else {                       //for IE < 9
        style.addRule(styleSel, styleDec, -1);
    }
}

I adapted the example at MDN This assumes you are using a class (that is already defined and applied) to add the :hover pseudo-selector to, but it could just as easily be an ID or element selector. If you were unable to add a class or style rule beforehand, you could also do that dynamically in much the same way (define class, define class:hover, then apply class to desired elements).

Post a Comment for "Set Style With :hover Javascript"