Click to See Complete Forum and Search --> : Changing a Div's background image onMouseOver


alecks
05-02-2007, 05:25 PM
I'm sure this is a very simple script but I have very little experience in JavaScript. I am trying to learn it and I would appreciate it if you help me create this effect :).

Style.css
#test{
background-image:url(images/bg1.gif);
height:100px;
width:100px;
}

and I imagine the HTML would look something like this, with the Javascript I have so far.


<html>
...
<script type="text/Javascript">
function changeBgImage (image , id) {
var element = getDocumentByID(id);
element.style.background-image = url(image);
}
</script>

<body>

<div id="test" onMouseOver="changeBgImage('images/bg2.gif','test')">
</div>

</body>
</html>

That's basically it. Any help is appreciated.

bosko
05-02-2007, 06:25 PM
Like this?

<html>
<head>
<style type="text/css">
#test {
background-image:url(images/bg1.gif);
height:100px;
width:100px;
}
</style>
<script type="text/javascript">
function changeBgImage (image, id) {
var element = document.getElementById(id);
element.style.backgroundImage = "url("+image+")";
}
</script>
</head>
<body>
<div id="test" onMouseOver="changeBgImage('images/bg2.gif', 'test')">
</div>
</body>
</html>

alecks
05-02-2007, 06:34 PM
Ah! Thank you very much! :D

tugboat
11-15-2007, 11:27 AM
What additional script needs to be included to have it return to the original image on a mouse exit?

sgreve
11-15-2007, 04:33 PM
Hey guys, could the above snippet be modified to work onClick and with multiple background images on one div? Ideally the background change would depend on which of a series of links was clicked.

Dahwan
02-05-2009, 07:39 PM
What additional script needs to be included to have it return to the original image on a mouse exit?


<div
id="test"
onMouseOver="changeBgImage('images/bg2.gif', 'test')"
onMouseOut="changeBgImage('images/bg1.gif', 'test')">
</div>

RyanMMalinoski
08-03-2009, 02:27 AM
this code does not account for the right side of the div tag. onmouseout works for the top left and bottom sides but not the right ideas?

RyanMMalinoski
08-03-2009, 02:41 AM
nevermind, i figured it out wasn't closing my div tag haha i am a genius

ashkanjj
08-03-2009, 05:54 AM
Can someone tell me with using the same method, how can you remove the image as you use "onMouseOut"??