简体   繁体   中英

Change background image dynamically on checked checkbox

Hi this is my first question in the stackoverflow community and I am having problems changing the background image of my webpage dynamically when a checkbox is checked

HTML:

<ul>
    <li><label for="Lines">Add Fun: </label><input type="checkbox" id="Lines" name="Lines" /></li>
</ul>

jQuery:

<script type="text/javascript">
        if ($('#Lines').is(':checked')) {
                    $("body").css({'background-image': 'url(http://upload.wikimedia.org/wikipedia/commons/d/d3/Mud_wrestling_couple.jpg)'});
        }
</script>

I want it to change the background of the body as soon as the checkbox is checked. The image is just a random one I found online. Think I might be overlooking something. Thanks for the help!

You may try this

​$(function(){
    $('#Lines').on('change', function(){
        if($(this).is(':checked')) 
        {
            $("body").css({ 'background-image': 'url(image url)' });
        }
        else $("body").css({'background-image':''});
    });
});​

Example .

Well, you need to do the check once the checkbox is altered.. so use the .change() event handler

<script type="text/javascript">
    $('#Lines').change(function(){
       if (this.checked){
          $("body").css({'background-image': 'url(http://upload.wikimedia.org/wikipedia/commons/d/d3/Mud_wrestling_couple.jpg)'});
       } else {
          // here you should do what you want when the user un-checks the checkbox..
       }
    });
</script>
$('#Lines').click(function ()
{
 if ($(this).is(':checked'))
 {
   $("body").css({'background-image': 'url(http://upload.wikimedia.org/wikipedia/commons/d/d3/Mud_wrestling_couple.jpg)'});
 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM