(onMouseOver): Background color changes, but background image won't change

Hello,

I am trying to write a piece of code that will change the background image of a div when an image is being mouse over, using the onMouseOver event. I had not luck, so I tried it changing the background color. Which works fine. I am confused to why the background color will change but not the image.

I have my photos saved in a separate folder, I have called it imgs, with the picture I am trying to access called Student2BG and it is saved as a JPG type. I thought at first I might not be accessing the image correctly. However, re-checking my code, I believe I have accessed the photo correctly.

Here is my code:

<!DOCTYPE html>
</html>
<head>
<link rel="stylesheet" href="Style.css">
</head>

<body>

<div id="StudentProfile">
<img src="imgs/Student1Profile.jpg" alt="Student One Profile Picture" height="200" width="200" onmouseover="onMouseOverStudent1();" onmouseout="onMouseOut();">
<br>
<img src="imgs/Student2Profile.jpg" alt="Student Two Profile Picture" height="200" width="200" onmouseover="onMouseOverStudent2();" onmouseout="onMouseOut();">
</div>



<script>

function onMouseOverStudent1(){
document.getElementById("StudentProfile").style.backgroundColor = "red";
}

function onMouseOverStudent2(){
document.getElementById("StudentProfile").style.backgroundImage = "imgs/Student2BG.jpg";
}

function onMouseOut(){
document.getElementById("StudentProfile").style.backgroundColor = "#D3D3D3";
}

</script>
</body>

</html>

You need to wrap the location with URL (you might need to fully qualify the url. Not sureā€¦)

function onMouseOverStudent2(){
document.getElementById("StudentProfile").style.backgroundImage = "url('imgs/Student2BG.jpg')";
}

Thanks. It worked.

Being new to Javascript, the URL bit through me off and I thought that would only be necessary if you were using an image off the internet.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.