PDA

View Full Version : JS changing CSS background image



sam150
28 Oct 2010, 09:02 AM
What I am trying to do is when a button is clicked in a link I want to run a function, which will change the background image of a div ID in an external CSS file in order to show the over state image.

Before I have just used the css a:hover method but want to try a different way.

So far I have this:

HTML

<a href="index.html" id="indexLink" onclick="indexNavBar()">Home</a>


External CSS

#navBar{
background-image:url(../html/images/navBar/navBar.jpg); <--- bit i want to change
}


External JS

Done a bit more reading and and came up with this but it aint working.


function indexNavBar(){
var imagePath = document.getElementById("navBar").style.backgroundImage;

if (imagePath == "url(../html/images/navBar/navBar.jpg)")
{
document.getElementById("navBar").style.backgroundImage = "url(../html/images/navBar/homeOver.jpg)";
} else {
document.getElementById("navBar").style.backgroundImage = "url(../html/images/navBar/navBar.jpg)";
}
}