views:

92

answers:

4

How to change HTML background with JavaScript Function? I need some simple function to change background from one image to another?

+1  A: 

Very simple like this:

function changeBGImage(){
     document.body.background = "image.jpg";
}

Hope this helps you

UPDATE

Or if you wanna use CSS (more elegant solution) with it, you could use:

<style>
.bg1 {
background-image: url(images/my_image.jpg); 
}
</style>

<body id="page_body">

<script>
function changeBGImage(whichImage){
     document.getElementById('page_body').className="bg1"
}
</script>
Marcos Placona
I don't think that's going to work.
Pointy
@Pointy: Why not?
SLaks
Well, for one thing "background" isn't a property of the `<body>` DOM object, at least not in all browsers. The CSS answer should work however and it's really the right way to do it anyway.
Pointy
A: 
function changeBGImage(whichImage){
     document.body.backgroundImage = "url(" + whichImage + ")";
}
Harmen
Does not work in Firefox or IE8.
Pointy
@Pointy, he missed the `style` property, it should be `document.body.style.backgroundImage = "url(" + whichImage + ")";`
CMS
+1  A: 

An alternative IFF using jquery

$("body").css("background-image", "url(/image.jpg)");
David Liddle
I think it's overkill to import an entire library (jQuery) only for this
Marcos Placona
That is correct HENCE why I put IFF (if and only if, AND in bold) jquery is being used!!
David Liddle
+1  A: 

Try something like this:

function newBackGround (element,background) {
   element.style.backgroundImage = "url("+background+")";
}

newBackground (myElement,"newBackground.jpg");
Jeff Fohl