PDA

View Full Version : Swapping background image onClick


edenexter
05-26-2010, 10:55 AM
Hello,

I've done some searching around but haven't quite found what I needed.
I'm working on a page with that has a section with an animated gif for background. The animation plays once, and I would like it to play again when a separate anchor is clicked using 'onClick'.

I've gotten this far:
<html>
<head>
<title>Swap Change Div Background Image test</title>

<style type="text/css">

#div1 {
width:300px;
height:300px;
background-image:url(img/cat1.gif);
}

</style>

<script language="javascript" type="text/javascript">
function changeDivImage()
{
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;

if(imgPath = "url(img/cat1.gif)")
{
document.getElementById("div1").style.backgroundImage = "url(img/cat2.gif)";
}
else
{
document.getElementById("div1").style.backgroundImage = "url(img/cat1.gif)";
}
}
</script>

</head>

<body>


<div id="div1">
</div>
<br />

<a href="#" onclick="changeDivImage()">Click</a>


</body>
</html>

It will swap once but won't swap back. Also I fear the gif might not play again when swapped back. Is this true?

help would be greatly appreciated

Dormilich
05-26-2010, 02:07 PM
if(imgPath = "url(img/cat1.gif)")


doesn’t anything strike here?

PS. you don’t need to declare imgPath as String object
var imgPath = document.getElementById("div1").style.backgroundImage;