Search code examples
javascriptinputradio-buttonlabel

JS return label background color


here's my HTML:

<body>
    <div class="container">
        <img src="2.png" />
        <div id="colorChange"></div>
    </div>

    <div class="colorChoice">
        <form id="colorChoiceForm">
            <ul id="colorListParent">
                <li class="noButton">
                    <input type="radio" name="colorGroup" value="aaa12" id="aaa12" />
                    <label style="background-color:#d21212" class="colorPick" for="aaa12"></label>
                </li>
                <li class="noButton">
                    <input type="radio" name="colorGroup" value="daaa" id="daaa"/>
                    <label style="background-color:#202020" class="colorPick" for="daaa"></label>
                </li>
            </ul>
        </form>
    </div>>
</body>

and JS:

function load() {
    document.getElementById("colorListParent").addEventListener("click", function(e){
        var bgrColor = (e.target.style.backgroundColor); 
        console.log(bgrColor);
        console.log(typeof bgrColor);
        document.getElementById("colorChange").style.backgroundColor = bgrColor;
    });
}

window.onload = load;

Until I binded labels with buttons with for/id script worked - bby that I mean background color of #colorChange changed to color of clicked label. Now var bgrColor returns two strings - first one of them is color I need, but the second one is empty and color of #colorChange doesn't change.

Where's problem?


Solution

  • Once you start using label[for], you'll have to approach it in a different way because your "click" event will be fired twice - once for the label and once for the radio button (which gets selected automatically. Here is a working fiddle and below is the changed JS code.

    function load() {
        document.getElementById("colorListParent").addEventListener("click", function(e){
            //alert(e.target.id);
            if(e.target.id) {
                var selector = 'label[for=' + e.target.id + ']';
                var label = document.querySelector(selector);
                var bgrColor = label.style.backgroundColor;
                //alert(bgrColor);
                //alert(typeof bgrColor);
                document.getElementById("colorChange").style.backgroundColor = bgrColor;
            }
        });
    }
    
    window.onload = load;