javascript onmouseover change background image

Palaniichuk Dmytro picture Palaniichuk Dmytro · Dec 29, 2015 · Viewed 8.1k times · Source

I need to create simple photo gallery with JavaScript. My code doesn't works

function upDate(previewPic){
document.getElementById('image').style.backgroundImage = "url('previewPic.src')";
document.getElementById('image').innerHTML = previewPic.alt;

In this function I should change the URL for the background image of the div with the id="image" to the source file of the preview image

HTML code:

<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()">

Answer

Wauky picture Wauky · Dec 31, 2015

function upDate(previewPic){
   var src = previewPic.getAttribute( "src" );
   var alt = previewPic.getAttribute( "alt" );
   document.getElementById('image').style.backgroundImage = "url('" + src + "')";
   document.getElementById('image').innerHTML = alt;
}

  function unDo(X){
   X = document.getElementById('image');
   X.style.backgroundImage = "url('')";
    document.getElementById('image').innerHTML = "Hover over an image below to display here";
  
}
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('');
    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%;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Photo Gallery</title>
	</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>