0

I'm trying to change the CSS of my website by the user clicking a div and when they do the website's background will turn into a gif, but I don't know how to do that on JavaScript!

here's my code

 function easterFun(){
     var changeBG = document.getElementById("body");
     changeEaster.setAttribute("style","background-image:url(eatser.gif)")

also my div wont do anything when it is clicked. it wont execute this code can someone tell me the problem pls?? Welcome to the Holiday Spirit website!!!

<div  id="easter"onclick="easterFun" style = "cursor: pointer"()>Easter!</div>
<div id = "xmas" onclick ="xmasFun()">Christmas</div>



</body>
</html>
Coolio
  • 21
  • 2
  • 7

3 Answers3

2

Use style.cssText or style.backgroundImage

Example:

function easterFun(){
     var changeBG = document.getElementById("body");
     changeBG.style.cssText = "background-image: url(eatser.gif)";
}

Or:

function easterFun(){
     var changeBG = document.getElementById("body");
     changeBG.style.backgroundImage = "url(eatser.gif)";
}

Note:

document.getElementById capture only elements with ID (eg. <div id="body">)

For get "body element" use: document.body (or document.getElementsTagName("body")[0]), eg.:

function easterFun(){
     var changeBG = document.body;
     changeBG.style.backgroundImage = "url(eatser.gif)";
}
Protomen
  • 9,471
  • 9
  • 57
  • 124
0

Please try this

changeEaster.style.backgroundImage = "url(eatser.gif)"; 
Ashish Mehta
  • 7,226
  • 4
  • 25
  • 52
0

You're very close. You need to change getElementById to getElementsByTagName and match your variables:

function easterFun(){
     document.getElementsByTagName("body")[0].setAttribute("style","background-image:url(eatser.gif)");
}

getElementsByTagName returns an array of objects, which is why after the function call, we access [0].

In the above, I have also removed the variable declaration for brevity.

Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129