change the background image of your body with javascript

notes and quirk solutions found over time
Post Reply
darknkreepy3#
Site Admin
Posts: 255
Joined: Tue Oct 27, 2009 9:33 pm

change the background image of your body with javascript

Post by darknkreepy3# »

It wasn't as simple as it seemed at first.

I thought it was:

Incorrect this *.background refers to the color of the background, like "#FF0000" or "#CCC" etc, not an image.
document.body.style.background="backgrounds/backart-index.jpg";

Incorrect this DOES refer to the image, but *.backgroundImage has NO idea what a string without 'URL' is.
document.body.style.backgroundImage="backgrounds/backart-index.jpg";

Incorrect this is almost perfect, but *.backgroundImage wants you to send the command in a string, like you would in html calling a function.
document.body.style.backgroundImage=url("backgrounds/backart-index.jpg");

Correct! this is perfect, the command is in a single quote, and the addy inside the command is in a double quote so as to not conflict with the single quotes { ' { " " } ' }
document.body.style.backgroundImage='url("backgrounds/backart-index.jpg")';

Also, remember to do this, so the page loads first (including the body itself...)

Code: Select all

<SCRIPT TYPE="text/javascript">
	window.onload=function()
		{
		//document.body.style.background="#ccc";
		//backgroundImage needs a string in single quotes 'url("*")'; *=addy 
		document.body.style.backgroundImage='url("backgrounds/backart-index.jpg")';
		}
</SCRIPT>

you can also do this if you are not at the root with your html or php page... make a $to_root variable marking how far away you are from the root folder for your site.

Code: Select all

<?php
$to_root="";
$galleryStr="";
?>
<html>
	<head>
		<link type="text/css" rel="stylesheet" href="<?php echo $to_root;?>css/splash.css" />
		<link type="text/css" rel="stylesheet" href="<?php echo $to_root;?>css/blurb.css" />
	</head>			
	<body>
			<div class="wrap">
				<div class="topBanner"><img src="banners/banner_splash.png" width="600px" /></div>
				<h3>3D | Programming | Design | Simulations | Forensics | Videography</h3>
				<a href="indexMain.php"><img src="iconz/enter_site.png" /></a>
				<div class="rightCol">
					<?php require $to_root."mS/map/introRight.html";?>
				</div>
			</div>
	</body>
</html>
<SCRIPT TYPE="text/javascript">
	window.onload=function()
		{
		//document.body.style.background="#ccc";
		//backgroundImage needs a string in single quotes 'url("*")'; *=addy 
		document.body.style.backgroundImage='url("<?php echo $to_root;?>backgrounds/backart-index.jpg")';
		}
</SCRIPT>
Post Reply