Hello, I am beginning to learn JS and am stuck on functions. What I am trying to do is write a function where the background image of a div changes when the user hovers their mouse over an image using the onmouseover event. Given the code below, the two objectives I am trying to achieve are:
-
Change the url for the background image of the div with the id = “image” to the source file of the preview image, AND then update the url for the background image of the div with the id = “image” back to the orginal on onmouseout.
-
Change the text of the div with the id = “image” to the alt text of the preview image using the onmouseover event.
Here’s the code I have so far:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Interactive Photo Gallery</title>
<!-- EMBEDDED CSS & JS -->
<style type="text/css">
body {
margin: 2%;
border: 1px solid black;
background-color: #b3b3b3;
}
#image{
line-height: 650px;
width: 575px;
height: 650px;
border: 5px solid black;
margin: 0 auto;
background-color: #8e68ff;
background-image: url(''); /* Do not hard-code the location here. */
background-repeat: no-repeat;
color: #FFFFFF;
text-align: center;
background-size: 100%;
margin-bottom: 25px;
font-size: 150%;
}
.preview{
width: 10%;
margin-left: 17%;
border: 10px solid black;
}
img{
width: 95%;
}
</style>
<script type="text/javascript">
/* <![CDATA[ */
function upDate(previewPic){
/* In this function I want to:
1) Change the url for the background image of the div with the id = "image" to the source file of the preview image
2) Change the text of the div with the id = "image" to the alt text of the preview image
*/
document.getElementById('image').style.backgroundImage=previewPic.src; // I don't know why this does change the background iamge of the div
document.getElementById('image').innerHTML = previewPic.alt;
}
function unDo(){
/* In this function you should
1) Update the url for the background image of the div with the id = "image" back to the orginal-image.
2) Change the text of the div with the id = "image" back to the original text.
*/
document.getElementById('image').innerHTML = "Hover over an image below to display here.";
}
/* ]]> */
</script>
</head>
<body>
<div id="image">Hover over an image below to display here.</div>
<img class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover="upDate(this)" onmouseout="unDo()">
<img class="preview" alt="With My Boy" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover="upDate(this)" onmouseout="unDo()">
<img class="preview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt="Young Puppy" onmouseover="upDate(this)" onmouseout="unDo()">
</body>
</html>