Search code examples
javascriptfunctioneventssliderhsl

How should I connect my sliders to the article element in JavaScript?


I need to create an HSL slider that will change the background color of the article element in my HTML. However, I can't figure out how to connect the slider to the background color.

I've been messing with it all day and reading but haven't come up with a solution yet, so I'm here for help.

This is the relevant JavaScript code I have right now:

var article = document.getElementsByTagName("article");
var backgroundColor = document.getElementById("backgroundColor");

var hSlider = document.getElementById("myRange1");
var sSlider = document.getElementById("myRange2");
var lSlider = document.getElementById("myRange3");

var makeHslString = function hsl(ih, is, il) {
    var hslString = "("+ ih + ", " + is + "%, " + il + "%)";
    return hslString;
    console.log("The result of the function is " + hslString);
}

hSlider.addEventListener("click", function(ev) {
    // alert("got a click!");
})

hSlider.addEventListener("input", function(ev) {
    article.style = makeHslString(0, 0, 0);
    article.style.backgroundColor = hSlider.value;
})

The sliders work perfectly fine and I know they work with my JavaScript because the alert event popped up, but I can't figure out how to change the color.

I just started programming, so the answer is probably something really simple I just haven't been able to figure out. Any help would be appreciated!

Thank you in advance, and please let me know if you need to see any more of the code!


Solution

  • This might help you get there: https://jsfiddle.net/1f72vdpL/. getElementsByTagName will return an array or collection, not an individual element. I think it's usually best to use getElementById or querySelector.

    var article = document.getElementById("article");
    
    
    var color = { h: 0, s: 0, l: 0 }
    var hSlider = document.getElementById("myRange1");
    var sSlider = document.getElementById("myRange2");
    var lSlider = document.getElementById("myRange3");
    
    var makeHslString = function hsl(ih, is, il) {
        var hslString = "hsl("+ ih + ", " + is + "%, " + il + "%)";
        color.h = ih
        color.s = is
        color.l = il
        return hslString;
    }
    
    
    hSlider.addEventListener("input", ev => {
        article.style.background = makeHslString(
            parseInt(ev.target.value),
            color.s,
            color.l,
        );
    })
    sSlider.addEventListener("input", ev => {
        article.style.background = makeHslString(
            color.h,
            parseInt(ev.target.value),
            color.l,
        );
    })
    lSlider.addEventListener("input", ev => {
        article.style.background = makeHslString(
            color.h,
            color.s,
            parseInt(ev.target.value),
        );
    })