Add style rules using JS on demand

by OmShiv

HTML

Choose Color: <input id="color-picker" type="color"/>
<br/>

<span class="tweet_text"></span>

CSS

.tweet_text::before {
    content: " Twitter Icon ";
    display: inline-block;
    border: 2px solid green;
    border-radius: 2px;
    margin: 2em;
    padding: 2em;
}

JavaScript

// Outside the event, one time

var styleTag = document.createElement('style'),
    styleSheet;

document.head.appendChild(styleTag);
styleSheet = styleTag.sheet || styleTag.styleSheet;

// inside rule

$('#color-picker').on('change', function(){
    var newval = $(this).val();
    if (styleSheet.cssRules.length > 0) {
        styleSheet.deleteRule(0);
    }
    
    styleSheet.insertRule(".tweet_text::before {" +
        "background-color: " + newval +
    "}", styleSheet.cssRules.length);
});