GROVER.
GROVER.

Reputation: 4378

RGB values not changing until first input has been altered

I have an extremely simple script on my webpage which allows users to change the background color of an element; based on the rgb slider values.

It works, however, in order for it to update the elements background rgb(), the uppermost input slider value has to have been changed.

The way the script is supposed to work, is when any of the slider values are changed, the background rgb() value is changed along with it.

This is my JavaScript:

var input = document.querySelector("input");

input.addEventListener("input", function(){

    var red = document.getElementById("red").value,
        green = document.getElementById("green").value,
        blue = document.getElementById("blue").value;

    var display = document.getElementById("display");

    display.style.background = "rgb(" + red + ", " + green + ", " + blue + ")";

});

And my HTML:

<div class="picker">
    Red <input type="range" min="0" max="255", step="1" id="red">
    Green <input type="range" min="0" max="255", step="1" id="green">
    Blue <input type="range" min="0" max="255", step="1" id="blue">

    <div id="display"></div>
</div>  

I feel like it may have something to do with document.querySelector("input"), however, I am unsure as I am pretty new to pure JavaScript.

Thanks.

Upvotes: 0

Views: 50

Answers (1)

Satpal
Satpal

Reputation: 133403

document.querySelector() returns single element thus it works for first input.

You need to use document.querySelectorAll() returns a list of the elements. You need to iterate it to bind event handler with individual element.

var input = document.querySelectorAll("input");
for (var i = 0; i < input.length; i++) {
    input[i].addEventListener("input", function() {
        var red = document.getElementById("red").value,
            green = document.getElementById("green").value,
            blue = document.getElementById("blue").value;

        var display = document.getElementById("display");
        display.style.background = "rgb(" + red + ", " + green + ", " + blue + ")";
    });
}
<div class="picker">
    Red
    <input type="range" min="0" max="255" , step="1" id="red">
    Green
    <input type="range" min="0" max="255" , step="1" id="green">
    Blue
    <input type="range" min="0" max="255" , step="1" id="blue">
    <div id="display">Yahooooooooooooo</div>
</div>

Upvotes: 2

Related Questions