[javascript] Setting CSS pseudo-class rules from JavaScript

here is a solution including two functions: addCSSclass adds a new css class to the document, and toggleClass turns it on

The example shows adding a custom scrollbar to a div

_x000D_
_x000D_
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass_x000D_
function toggleClass(elem, theClass, newState) {_x000D_
  var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');_x000D_
  var add = (arguments.length > 2 ? newState : (elem.className.match(matchRegExp) === null));_x000D_
_x000D_
  elem.className = elem.className.replace(matchRegExp, ''); // clear all_x000D_
  if (add) elem.className += ' ' + theClass;_x000D_
}_x000D_
_x000D_
function addCSSclass(rules) {_x000D_
  var style = document.createElement("style");_x000D_
  style.appendChild(document.createTextNode("")); // WebKit hack :(_x000D_
  document.head.appendChild(style);_x000D_
  var sheet = style.sheet;_x000D_
_x000D_
  rules.forEach((rule, index) => {_x000D_
    try {_x000D_
      if ("insertRule" in sheet) {_x000D_
        sheet.insertRule(rule.selector + "{" + rule.rule + "}", index);_x000D_
      } else if ("addRule" in sheet) {_x000D_
        sheet.addRule(rule.selector, rule.rule, index);_x000D_
      }_x000D_
    } catch (e) {_x000D_
      // firefox can break here          _x000D_
    }_x000D_
    _x000D_
  })_x000D_
}_x000D_
_x000D_
let div = document.getElementById('mydiv');_x000D_
addCSSclass([{_x000D_
    selector: '.narrowScrollbar::-webkit-scrollbar',_x000D_
    rule: 'width: 5px'_x000D_
  },_x000D_
  {_x000D_
    selector: '.narrowScrollbar::-webkit-scrollbar-thumb',_x000D_
    rule: 'background-color:#808080;border-radius:100px'_x000D_
  }_x000D_
]);_x000D_
toggleClass(div, 'narrowScrollbar', true);
_x000D_
<div id="mydiv" style="height:300px;width:300px;border:solid;overflow-y:scroll">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus_x000D_
  a diam volutpat, ullamcorper justo eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit_x000D_
  nec sodales sodales. Etiam eget dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui. Lorem ipsum dolor sit amet, consectetur_x000D_
  adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus a diam volutpat, ullamcorper justo_x000D_
  eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit nec sodales sodales. Etiam eget_x000D_
  dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui._x000D_
</div>
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to pseudo-class

How to position a CSS triangle using ::after? Indent starting from the second line of a paragraph with CSS Css pseudo classes input:not(disabled)not:[type="submit"]:focus CSS3 :unchecked pseudo-class CSS :selected pseudo class similar to :checked, but for <select> elements How to write :hover condition for a:before and a:after? CSS Pseudo-classes with inline styles How to select the first, second, or third element with a given class name? What is the difference between :focus and :active? Setting CSS pseudo-class rules from JavaScript

Examples related to css-in-js

Setting CSS pseudo-class rules from JavaScript