Reputation: 63
How i can change background color automatically with HTML5 colorpicker? Currently after i have selected my color, i have to click button to change the background color. I tried to use while (1) loop to change it automatically, but it just crashes my browser.
https://jsfiddle.net/VortexP/eh4t17fv/4/
HTML:
<input type="button" id="fullscreenbutton" onclick="fcolor()"> Button
<br>
<input type="color" id="colorpickerbutton" name="color"> Colorpicker
<br>
<div id="overlay" ></div>Result
JAVASCRIPT:
function fcolor () {
var color = document.getElementById("colorpickerbutton").value;
document.getElementById("overlay").style.backgroundColor = color;
}
Upvotes: 2
Views: 1205
Reputation: 1258
you don't need any infinite while loops. You need to attack an eventListener to yout input.
<input type="color" id="colorPickerButton" name="color">
document.querySelector("input").addEventListener("input", function() {
document.body.style.background = this.value;
});
Upvotes: 1
Reputation: 588
The reason why the while(1)
loop crashes your browser is because JavaScript is single-threaded. That means all of your JavaScript runs sequentially. You can never have two JavaScript functions running at the exact same time.
So, while(1)
blocks all of your other JavaScript from executing, and even freezes the webpage itself because it blocks all browser events.
What you want to do is call a function only when the color input changes :)
That would look like this:
HTML:
<input type="color" id="colorpickerbutton" name="color" onChange="changeColor(this.value)">
JavaScript:
function changeColor(newColor) {
document.getElementById("overlay").style.backgroundColor = newColor;
}
Upvotes: 2