user1524652
user1524652

Reputation: 41

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!

Upvotes: 3

Views: 4870

Answers (3)

David Houde
David Houde

Reputation: 4778

$('#Lines').click(function ()
{
 if ($(this).is(':checked'))
 {
   $("body").css({'background-image': 'url(http://upload.wikimedia.org/wikipedia/commons/d/d3/Mud_wrestling_couple.jpg)'});
 }
});

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

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>

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

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.

Upvotes: 3

Related Questions