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
2010-04-11 21:04:31
I don't think that's going to work.
Pointy
2010-04-11 21:05:33
@Pointy: Why not?
SLaks
2010-04-11 21:06:12
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
2010-04-11 21:11:14
A:
function changeBGImage(whichImage){
document.body.backgroundImage = "url(" + whichImage + ")";
}
Harmen
2010-04-11 21:06:37
+1
A:
An alternative IFF using jquery
$("body").css("background-image", "url(/image.jpg)");
David Liddle
2010-04-11 21:07:14
I think it's overkill to import an entire library (jQuery) only for this
Marcos Placona
2010-04-11 22:54:49
That is correct HENCE why I put IFF (if and only if, AND in bold) jquery is being used!!
David Liddle
2010-04-12 08:08:22
+1
A:
Try something like this:
function newBackGround (element,background) {
element.style.backgroundImage = "url("+background+")";
}
newBackground (myElement,"newBackground.jpg");
Jeff Fohl
2010-04-11 21:08:46