Tushar
Tushar

Reputation: 97

Control color of multiple divs using input slider?

I want to create a temperature slider which will change the color of the div(s) based on their melting and boiling points. These values are stored in the following array

var elements = {
    hydrogen: {"m_point": "14.01", "b_point": "20.28"},
    helium: {"m_point": "0", "b_point": "4.22"}, 
    //----------so on----------------------------
};

and these are the divs whose colors have to be changed

<div id="hydrogen"><em>1</em>H<p>Hydrogen</p></div>
<div id="helium"><em>2</em>He<p>Helium</p></div>
<!---------so on----------------------------------->

I can't figure out how can I use the value returned by the slider, compare that value with the melting/boiling points given, and change color of div according to that(e.g blue if value>=m_point, red if value>=b_point etc.). Basically change color when the state of elements will change from solid->liquid, liquid->gas and vice-versa. I can't use if else statements as I have to specify color each and every time for each element.

Upvotes: 0

Views: 62

Answers (1)

Ivan Modric
Ivan Modric

Reputation: 619

Since you didn't provide information about your slider I guess it works and you can successfully retrieve the temperature.

It would be easiest if the relevant elements (the ones that should change color depending on temperature) had a common class (here we'll use class="element").

var $element = $('.element');

We'll assume var temperature to be the temperature set by the slider.

I would also change the temperatures in your object from strings to numbers. ("m_point":14.01,"b_point":20.28)

Now all we have to do is iterate through these relevant elements like so:

$.each($element, function ( key, value ) {
    var id = value.id;
    if (temperature >= elements[id].b_point) {
        // apply the background-color for gas state
        value.style.backgroundColor = "red";
    } else if (temperature >= elements[id].m_point) {
        // apply the background-color for liquid state
        value.style.backgroundColor = "green";
    } else {
        // apply the background-color for solid state
        value.style.backgroundColor = "blue";
    }
});

What we have done is "navigate" the object elements with square bracket notation allowing us to use the variable id. This also means it only works as long as the id-attribute of the div matches one of the properties of elements.

PS.:

You'll of course need to bind the script to some kind of event for it to be executed. I created a codePen for you in which it is bound to the change event of the input element.

Upvotes: 1

Related Questions