3

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!

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

16,500 rep! Wow! :) That's a lot... I have 200. :) But you deserve it all. ;) You get rep by being helpful...
1

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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.