Search code examples
jscolor

jsColor.js Change background color of element


I am trying to change the background color of an element using this simple color picker but I am getting no results and no console errors.

<div class="col-md-3">
    <div class="home-icon">
        <div class="home-icon-text">
            <h3>Home</h3>
        </div>
    </div>
    <div class="icon-color text-center">
        <input class="color {onImmediateChange:'updateInfo(this);'}">
    </div>
</div>

function updateInfo(color) {
    var a = color.rgb[0];
    var b = color.rgb[1];
    var c = color.rgb[2];

    $(this).parent().prev().css("background", "rgb(" + a + "," + b + "," + c + ")");
};

Solution

  • I believe that there might be two problems:

    1. That this refers to the global window object inside of the function when it is called. You can do what you want by giving the div an id, then selecting it and applying the background.

    2. "rbg("+a+","+b+","+c+")" doesn't seem to work. I think you could multiply the numbers by 255 and then round them with Math.Floor.

    Try the following:

    <script type="text/javascript" src="jscolor/jscolor.js"></script>
    <script type="text/javascript">
    function updateInfo(color) {
        var a = Math.floor(color.rgb[0] * 255);
        var b = Math.floor(color.rgb[1] * 255);
        var c = Math.floor(color.rgb[2] * 255);
        var color = "rgb(" + a + "," + b + "," + c + ")";
        var node = document.getElementById("colorme");
        node.style.backgroundColor = color;
    }
    </script>
    
    <div class="col-md-3" id="colorme">
        <div class="home-icon">
            <div class="home-icon-text">
                <h3>Home</h3>
            </div>
        </div>
        <div class="icon-color text-center">
            <input class="color {onImmediateChange:'updateInfo(this);'}" >
        </div>
    </div>
    

    Hope that helps!