0

I'm trying to change the alt text and background image of my div with the id = image, using javascript.

I have tried using document.getElementById('image').innerHTML = this.alt to change the text but it doesn't work.

I have also tried using document.getElementById('image').style.backgroundImage = this.src

Can anyone provide me with some insight?

function upDate(previewPic) {
  document.getElementById('image').style.backgroundImage = this.src;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Photo Gallery</title>
  <link rel="stylesheet" href="css/gallery.css">
  <script src="js/gallery.js"></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>
thordarson
  • 5,943
  • 2
  • 17
  • 36
TechWiz
  • 1
  • 1

1 Answers1

0

As @Toastrackenigma mentioned, the javascript keyword this in a function only refers to the function context, not the previewPic parameter that you're looking for. You can read more about it here. You can use onmouseover="upDate(this)" in HTML since the this keyword in the HTML refers to the image, but the this keyword in JS does not.

What you're looking for might be something like this:

function upDate(previewPic){
    document.getElementById('image').style.backgroundImage = `url(${previewPic.src})`;
}

However, as stated in this post, a background image is only for decoration and shouldn't have any semantic meaning, so it shouldn't have an alt attribute. You might be considering a title attribute for the div element, which would display a small tooltip on hover. Likewise, you would use

document.getElementById('image').title = previewPic.alt;
Parzival
  • 2,051
  • 4
  • 14
  • 32