3

I'd like to know how to change the background of the #new-quote:before element because using information in this thread: Changing width property of a :before css selector using JQuery, I've learned we can only do it using special techniques and only content property of CSS. But what about other properties of CSS, like the background?

 colors = [
  "#ff9966",
  "#7f00ff",
  "#396afc",
  "#0cebeb",
  "#06beb6",
  "#642b73",
  "#36d1dc",
  "#cb356b",
  "#3a1c71",
  "#ef3b36",
  "#159957",
  "#000046",
  "#007991",
  "#56ccf2",
  "#f2994a",
  "#e44d26",
  "#4ac29a",
  "#f7971e",
  "#34e89e",
  "#6190e8",
  "#3494e6",
  "#ee0979"
],
randomNumber = Math.floor(Math.random() * colors.length);

What I've used for my project is:

var addRule = function(sheet, selector, styles) {
if (sheet.insertRule) 
  return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule)
  return sheet.addRule(selector, styles);
}

addRule(document.styleSheets[0], "#new-quote:before", "content: colors[randomNumber]");

So yeah, it works with the content property, but what about the background one?

addRule(document.styleSheets[0], "#new-quote:before", "content: colors[randomNumber]");

Nope :( Here is my codepen for full project code:

See the Pen xpgBNv by Lukas (@Kestis500) on CodePen.

This line of code fixed everything! :)

$('head').append("<style>#new-quote:before{background:"+ colors[randomNumber] + ";}</style>");

1 Answers1

3

You can create a style tag with your custom css color and append it to head

See Example

colors = [
  "#ff9966",
  "#7f00ff",
  "#396afc",
  "#0cebeb",
  "#06beb6",
  "#642b73",
  "#36d1dc",
  "#cb356b",
  "#3a1c71",
  "#ef3b36",
  "#159957",
  "#000046",
  "#007991",
  "#56ccf2",
  "#f2994a",
  "#e44d26",
  "#4ac29a",
  "#f7971e",
  "#34e89e",
  "#6190e8",
  "#3494e6",
  "#ee0979"
],
randomNumber = Math.floor(Math.random() * colors.length);
$('head').append("<style>.div1:before{background:"+ colors[randomNumber] + "}</style>");
.div1:before {
  content: 'before  ';
  display: inline-block;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="div1">container2</div>
Chiller
  • 9,520
  • 2
  • 28
  • 38