0

I have to change the background of the div when I hover over the image, but somehow it's not detecting image though the URL is displayed in the console. I have no idea of jQuery. Thank you.

function upDate(previewPic) {
  var divblock = document.getElementById('image');
  var img = previewPic.src;
  console.log(img);
  divblock.style.backgroundImage = img;
  divblock.innerHTML = previewPic.alt;
}
<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()">

2
  • Your code seems to work, as I understand it. The only error is because you've not provided the unDo() function in the example Commented Feb 27, 2020 at 9:44
  • your code works okay as @RoryMcCrossan said. just remove the onmouseout() because you don't require it, anyhow on hover of another image will upDate() is always going to fire. or else create a blank function and return true in unDo() Commented Feb 27, 2020 at 9:51

1 Answer 1

3

You need to pass the image source with url like divblock.style.backgroundImage = "url('url of the source')";

function upDate(previewPic) {
  var divblock = document.getElementById('image');
  var img = previewPic.src;
  divblock.classList.add('hoverDiv');
  divblock.style.backgroundImage = 'url(' + img + ')';
  divblock.innerHTML = previewPic.alt;
}

function unDo() {}
.hoverDiv {
  width: 500px;
  height: 500px;
  margin-bottom: 20px;
  color:red;
}
<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()">

Sign up to request clarification or add additional context in comments.

2 Comments

Why is the URL quotes used in quite a weird way. Thanks for modification.
it is because img is a variable and you need to concat with url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.