How to change the background image of a label using CSS with JavaScript

20,422

You seem to just be missing some quotes (the value of style.backgroundImage should be a string):

function func()
{
    var label = document.getElementById('label-interest1');
    if(document.getElementById('interest_inet').checked)
    {
        label.style.backgroundImage = 'url(images/internetbutton.gif)';
    }
    else
    {
        label.style.backgroundImage = 'url(internetbuttonchecked.gif)';
    }
}
Share:
20,422
Nick
Author by

Nick

Updated on June 16, 2020

Comments

  • Nick
    Nick almost 4 years

    This one is a real headache. I have three checkboxes in a form that I have labels for, and the labels have background images set with CSS, the question is, how exactly do I get my JavaScript to change the image from current image to a second image when it is clicked and select the checkbox. From what I know of javascript, it should work, any ideas? Also, it does have to be this way due to previous issues with i.e. 7 and 8.

    HTML

    <input type="checkbox" name="interest1" id="interest1" value="interested"style="display:block">
    <input type="checkbox" name="interest2" id="interest2" value="interested"style="display:block">
    <input type="checkbox" name="interest3" id="interest3" value="interested"style="display:block">
    <p align="center">
    <label for="interest_inet" id="label-interest1" onClick="func()"></label>
    

    CSS:

    label {
        border:1px solid red;
        display:inline-block;
    }
    
    #label-interest1 {
        background-image: url(images/internetbutton.gif);
        width: 152px;
        height:152px;
    }
    

    JavaScript:

    <script type="text/javascript">
    function func()
    {
        if(document.getElementById('interest_inet').checked)
        {
            document.getElementById('label-interest1').style.backgroundImage=url(images/internetbutton.gif);
        }
        else
        {
            document.getElementById('label-interest1').style.backgroundImage=url(internetbuttonchecked.gif);
        }
    }
    </script>
    

    Here is a live code example