2

I have a simple question, I need to make a switch/button in which the user clicks it to toggle the background image to on or off

Here's the code:

body style = "background-image: url('WebsiteBG.jpg')"

And here's the CSS for it:

<style>
  body{
    background-size: cover; 
    background-repeat: no-repeat;  
    background-attachment: fixed 
  }
</style>
depperm
  • 10,606
  • 4
  • 43
  • 67
Sami Nofal
  • 57
  • 1
  • 11
  • 2
    have you attempted any js or jquery? – depperm Jul 22 '15 at 13:48
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it **in the question itself**. See [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve) – Paulie_D Jul 22 '15 at 14:03
  • possible duplicate of [Switching a DIV background image with jQuery](http://stackoverflow.com/questions/253689/switching-a-div-background-image-with-jquery) – Zakaria Acharki Jul 22 '15 at 14:10

2 Answers2

3

Well, you can do this using jQuery or javaScript. The basic idea would be to toggle the class of the body tag. See an example below :

JavaScript Solution :

HTML:

<body>
    <div style="color:red;">Some random text here</div>
    <input type="button" id="btnBack" value="Toggle Background" />
</body>

CSS:

body {
    background-size: cover; 
    background-repeat: no-repeat;  
    background-attachment: fixed 
  }

.BgClass {
    background-image: url('http://freedomwallpaper.com/wallpaper2/funky-wallpaper-hd.jpg');
}

javaScript

var btnBack = document.getElementById('btnBack');
btnBack.addEventListener('click',function() {
    document.body.classList.toggle('BgClass');
});

You can see this here -> http://jsfiddle.net/qagdvft6/

jQuery Solution

$('#btnBack').click(function() {
    $('body').toggleClass('BgClass');
});
body{
    background-size: cover; 
    background-repeat: no-repeat;  
    background-attachment: fixed 
  }

.BgClass {
    background-image: url('http://freedomwallpaper.com/wallpaper2/funky-wallpaper-hd.jpg');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
    <div style="color:red;">Some random text here</div>
    <input type="button" id="btnBack" value="Toggle Background">
</body>
Satwik Nadkarny
  • 5,086
  • 2
  • 23
  • 41
0

This is a pretty simple thing to achieve using jQuery.

You can see my example here: http://jsfiddle.net/qwnLj4tj/

With jQuery I am toggling a style class on the body when the button is clicked:

$('.my-button').click(function() {
    $('body').toggleClass('active-class');
    return false;
});

And with css I am just applying the styles for the toggleClass:

body.active-class {
    background: url('URL/TO/BGIMAGE.EXT');
}
Levi Cole
  • 3,561
  • 1
  • 21
  • 36