0

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.

3
  • 1
    are you encapsulating that js to make sure the DOM is loaded before the JS is? put the JavaScript in (function(){ ... })() and try again Commented Feb 9, 2017 at 9:50
  • Added the anon function to make sure DOM is loaded and still not working :( Commented Feb 9, 2017 at 9:52
  • It seems to be working fine, rules are added to the stylesheet, check the object in console here jsfiddle.net/zsz2xxej Commented Feb 9, 2017 at 9:59

1 Answer 1

2

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" />

Sign up to request clarification or add additional context in comments.

1 Comment

another fix : you could add the class same as the name to view live the changes <input type="color" class="seconds-hand" name="seconds-hand" value="#0c82cc" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.