0

I have a colour picker widget on my page. I'm trying to attach an event handler that will take the selected colour and apply a list of CSS rules to an iFrame on my page. The iFrame is on the same domain as my page, so updated the css inline isn't an issue.

The issue is that I need to use pseudo class selectors (like :hover etc) in some of my styles, which cant be done inline. I could make a style element and append it to the head of my iFrame, but that would mean a new element gets added each time a new colour is picked. Is there any way to 'replace' the style element each time a colour is picked? Or alternatively, is there an easier solution to my problem?

Phil O'kelly
  • 161
  • 1
  • 3
  • 14
  • 1
    You could simply assign to the `textContent` of the ` – CertainPerformance Oct 11 '18 at 04:01
  • This might help? https://stackoverflow.com/questions/1033156/how-to-write-ahover-in-inline-css – Electron Oct 11 '18 at 04:14

1 Answers1

0

You can use CSS-Variables for this.

Define your colors to ':root' in your css file:

:root{
    --myColor: red;
    --mySecondColor:green;
}

then set the colorProperties in your elements like this:

button{
    background-color: var(--myColor);
    padding:10px;
}
div{
    color: var(--mySecondColor);
    padding:10px;
}

Now in JavaScript you can change these properties globally

document.documentElement.style.setProperty('--myColor','blue');
document.documentElement.style.setProperty('--mySecondColor','orange');

Or change it just local

document.querySelector('button').style.setProperty('--myColor','blue');
Andre
  • 458
  • 5
  • 10
  • Would like to do this, but unfortunately IE needs to be supported – Phil O'kelly Oct 12 '18 at 03:53
  • Ugh IE. Then it becomes a bit more tricky. So you either could use the Javascript `mouseover` and `mouseout` events instead of the `:hover` or if you have an inline `style` Tag you read into `document.styleSheets` and `stylesheet.insertRule(rule,index)`. (create a new rule on the fly and insert in the existing sheet) Those are the 2 other methods which I can think of. I hope it helps – Andre Oct 12 '18 at 08:25