andy jones
andy jones

Reputation: 922

Vanilla javascript - insertRule CSS not working

I currently have 3 inputs which are colour pickers.

<input type="color" name="seconds-hand" value="#0c82cc" />
<input type="color" name="minutes-hand" value="#0c82cc" />
<input type="color" name="hours-hand" value="#0c82cc" />

Ive then written some javascript to find each one of these and update the styles in the header:

const input = document.querySelectorAll('input');
const sheets = document.styleSheets;
const sheet = document.styleSheets[0];

function handleUpdate(){
    const element = document.getElementsByClassName(this.name);
    sheet.insertRule(`.${this.name} { background-color: ${this.value} }`);
    console.log(`.${this.name} { background-color: ${this.value} }`);
}
input.forEach(input => input.addEventListener('change', handleUpdate));
input.forEach(input => input.addEventListener('mousemovement', handleUpdate));

The console log is returning the correct style to add to the style sheet, but nothing is being added. Am i using the incorrect js .inserRule ? I cant figure out why it isn't changing.

Any help would be great.

Upvotes: 0

Views: 681

Answers (1)

Vladu Ionut
Vladu Ionut

Reputation: 8193

The elements you were trying to find weren't in the DOM when the script ran. To fix this you can execute the code on window.onload event or DOMContentLoaded (document ready )

window.onload = function(){
const input = document.querySelectorAll('input');
const sheets = document.styleSheets;
const sheet = document.styleSheets[0];

function handleUpdate(){
    const element = document.getElementsByClassName(this.name);
    sheet.insertRule(`.${this.name} { background-color: ${this.value} }`);
    console.log(`.${this.name} { background-color: ${this.value} }`);
}
input.forEach(input => input.addEventListener('change', handleUpdate));
input.forEach(input => input.addEventListener('mousemovement', handleUpdate));
}
<input type="color" class="seconds-hand" name="seconds-hand" value="#0c82cc" />
<input type="color" class="minutes-hand" name="minutes-hand" value="#0c82cc" />
<input type="color" class="hours-hand" name="hours-hand" value="#0c82cc" />

Upvotes: 2

Related Questions