Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change #new-quote:before background using JQuery or JavaScript?

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>");
like image 445
Lukas Naujokaitis Avatar asked Sep 17 '25 07:09

Lukas Naujokaitis


1 Answers

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>
like image 150
Chiller Avatar answered Sep 19 '25 01:09

Chiller