Log in

View Full Version : Chaging Div background



rockstrongo
09-25-2007, 10:16 AM
Hello all, hopefully one of you lovely talented people will be able to help (who says flattery will get you nowhere).

I've got a list of links in a table inside a container div. Next to this is another div (with an ID of 'bookjackets'). I'd like it so that whenever someone mouseovers one of these links, the background image of 'bookjackets' is changed. I'd like it so that each link sets a different background image.

I've done a few searches for something like this, but the only thing I've been able to find is scripts that change the div a link is contained in. With this, I want to change a different div than the one the link is contained in. I'm very new to Javascript, I can implement stuff and just about understand what's going on, but all the stuff I've tried to write myself has resulted in loads of errors.

If someone could help, I'll send them a great big digital hug, and a metaphysical million dollars.

Thanks

codeexploiter
09-25-2007, 11:25 AM
You can achieve this by using JavaScript in two ways:

(1) Whenever the user clicks on the links you can invoke a JavaScript function that know which image needs to be loaded and change the background image of the div you want. The following example demonstrate this one.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
#test {
width: 750px;
border: 1px dotted #ff0000;
height: 300px;
}
</style>
<script type="text/javascript">
function changeDivBGround(imgName) {
document.getElementById('test').style.backgroundImage = "url("+imgName+")";
}
</script>
</head>
<body>
<p>
<a href="#" onclick="changeDivBGround('tables2tabs.jpg'); return false;">link 1</a> <br />
<a href="#" onclick="changeDivBGround('tabletabs.gif'); return false;">link 1</a>
</p>
<div id="test"></div>
</body>
</html>


* If the images are not in the same folder of your html page make sure that you are passing the path also along with the image name.

(2) In this method you'll have different style classes in your CSS say for example each link has their own style with the background image you want to load in the div element. Whenever the user clicks on the links you'll change the div's class using JavaScript something like the following code:



function changeDivBGround(linkId) {
var obj = document.getElementById('test');
obj.className = linkId +'_class';
}


The assumption in this case is we'll have class names based on the link IDs we mention in the hyperlinks say for example if the first link has a id 'first_link' then the style needs to be applied on the div would be 'first_link_class'.

rockstrongo
09-25-2007, 02:03 PM
Amazing! thanks for your help, that's perfect. I'm going to be using number 1.

::hug::
::$1000000::