0

I'm doing a Coursera assignment that requires me to make the JavaScript code change the background image with the onmouseover event, and then get it back to normal with the onmouseout event as well as putting the alt text of the images in the front every time the event happens, but I've tried a lot of coding these last few days, and the code doesn't work at all, and I don't know why.

HTML:

<div id = "image">Hover over an image below to display here</div>

<img class = "preview" alt = "Beautiful kitten"
src = "https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg"
onmouseover = "update(this)"
 onmouseout = "undo()"/>

<img class = "preview" alt = "Pretty Kitty" 
src = "https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg"
onmouserover = "update()" onmouseout = "undo()"/>

<img class = "preview" alt = "Baby cat"
src = "https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover = "update(this)" onmouseout = "undo()"/>

JS:

    var originalBackground;
function update(previewPic){
/* In this function I should 
    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 
    */
   previewPic = document.getElementsByClassName("preview");
   document.getElementById("image").src = previewPic;

    document.getElementById("image").innerHTML = img.getAttribute("alt");


}


function undo(){

    document.getElementById("image").style.backgroundImage = "";

}
2
  • document.getElementsByClassName returns an HTMLCollection; you need document.getElementsByClassName("preview")[0] to get the first one.
    – user5734311
    Sep 22, 2019 at 22:37
  • @Chris that would just show the first image for any mouse over. Sep 22, 2019 at 22:57

4 Answers 4

2

There are many ways you can approach solving the problem you set out above but here is one approach (using ES2015+ syntax).

Please do ask questions in the comments below if there is anything in the code that seems unclear or counter-intuitive and I can explain what each section of the code is doing.

Working Example:

const mainImage = document.getElementById('image');
const previews = [... document.getElementsByClassName('preview')];

const update = (e) => {
  mainImage.style.backgroundImage = 'url("' + e.target.src + '")';
  mainImage.style.backgroundSize = 'contain';
  mainImage.style.backgroundRepeat = 'no-repeat';
  mainImage.style.backgroundPosition = 'center';
  mainImage.textContent = e.target.alt;
}

const undo = () => {
    mainImage.style.backgroundImage = '';
    mainImage.textContent = 'Hover over an image below to display here';
}

previews.forEach((preview) => {
  preview.addEventListener('mouseover', update, false);
  preview.addEventListener('mouseout', undo, false);
});
#image {
  float: left;
  width: 300px;
  height: 150px;
  text-align: center;
  text-shadow: 1px 1px 4px rgb(255, 255, 255), 1px -1px 4px rgb(255, 255, 255), -1px -1px 4px rgb(255, 255, 255), -1px 1px 4px rgb(255, 255, 255);
}

.preview {
  width: 100px;
}
<div id="image">Hover over an image below to display here</div>

<img class="preview" alt="Beautiful kitten"
src = "https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg" />

<img class="preview" alt="Pretty Kitty" src = "https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg" />

<img class="preview" alt="Baby cat"
src = "https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" />


Question: Did you use const instead of function? if so, why?

1) In earlier versions of Javascript (before 2015), we declare a function like this:

function myFunction() { 

  [... code here...]

}

In versions of Javascript from 2015 onwards (sometimes referred to as ES6+ or ES2015+), we more usually declare a function as a variable like this:

var myFunction = () => {

  [... code here...]

}

This has several advantages (which you don't really need to worry about right now) but the main point is that it does the same thing as the syntax you're used to... it's just that instead of the keyword function before the parens (), there is now a fat arrow => after the parens.

Of course, you'll have noticed that I declared the variable using var in the example immediately above, whereas I used const in my answer.

That's because, again, in versions of Javascript from 2015 onwards when we do declare a variable (any variable), we more usually declare a function using the keywords:

  • let
  • const

We use let (for variables which have contents which are likely to change in future) and const (for variables which have contents which will always remain the same).


Question: What does the syntax update = (e) => { mean?

So, from the answer above, we now see that:

const update = () => {}

means pretty much the same as:

function update() {}

So the only thing left to understand here is the e in (e).

Here is what e means:

Any function optionally contains parameters - data variables which can be fed into the function. This is what the parens do when you declare a function - they contain all the parameters you will be processing in the function.

Quite often, the function doesn't require any parameters at all and that is why when you see functions declared, you quite often see: (). It means there will be no parameters passed to this function.

In this case e (sometimes referenced as event, though it can be referenced as anything) is quite a special parameter.

It exists always and whenever you create an event listener like mouseover, mouseout (also click, change, resize, scroll etc.)

When you reference the event object in a function which runs after an event listener fires, you can then access a number of really useful properties:

  • event.target
  • event.type
  • event.timeStamp etc.

In this case I am using event.target (or e.target) so that when the event fires and the function runs, the function knows which image fired the event, because that image was the target of the event.


Question: What do the multiple quotes inside quotes in mainImage.style.backgroundImage = 'url("' + e.target.src + '")'; mean?

The line

mainImage.style.backgroundImage = '[VALUE HERE]';

updates the CSS background-image style of mainImage with a string value (contained in single quotes ').

We can see that the single quotes belong to javascript - they contain the javascript value.

If we knew in advance the url of the image we wanted to add (and it was always the same) we could write:

mainImage.style.backgroundImage = 'url("my-image.jpg")';

Here the single quotes belong to javascript - they contain the javascript value.

The double quotes belong to CSS - they contain the CSS value my-image.jpg.

We can now move to a slightly more advanced step, where we do not know in advance the url of the image we want to add.

The value is: e.target.src

So, somehow, we need to present that as the CSS value.

But e.target.src doesn't mean anything in CSS.

So we can't simply write:

'url("e.target.src")'

Instead (this is the key) we have to break out of CSS syntax, add the variable and then add the rest of the CSS syntax. We can achieve this with:

 'url("'  +  e.target.src  +  '")'

This can be understood as:

'JS string contained in sinqle quotes' + actualJSValue + 'another string'

Thus, the finished line ends up as:

mainImage.style.backgroundImage = 'url("' + e.target.src + '")';
4
  • 2
    I have a small question regarding the declaration of the function, did you use const instead of function? if so, why? Also, what does it syntactically mean "update = (e) => {" ? I'm sorry if it looks obvious, I'm new in JavaScript :D Sep 22, 2019 at 23:48
  • 1
    As I'm re-reading your code, I don't understand this line of code below: mainImage.style.backgroundImage = 'url("' + e.target.src + '")'; What do the multiple quotes inside quotes mean? are they parameters levels? Thank you for your patience. Sep 23, 2019 at 0:07
  • Great questions, Valerie. I'll answer them in turn above. Do keep asking if you have any further questions.
    – Rounin
    Sep 23, 2019 at 8:48
  • Thanks alot @Rounin.in my case I was passing the wrong image url Sep 3 at 18:42
1

All your <img> elements have the same class preview. When you call document.getElementsByClassName("preview") you get a collection of the three elements.

You need to get the specific element that you mouse over. You already pass that in with a parameter this but overwrite the value when you call document.getElementsByClassName("preview").

Note: You have a typo onmouserover = "update()" remove the extra r.

function update(previewPic){
/* In this function I should 
    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").setAttribute('style', 'background-image: url(' +  previewPic.getAttribute("src") + ')');
   document.getElementById("image").innerHTML = previewPic.getAttribute("alt");
}


function undo(){
    document.getElementById("image").style.backgroundImage = "";
    document.getElementById("image").title = "";
}
#image, 
.preview { 
  width : 100px; 
  min-height: 100px; 
  background-size: contain;
  background-repeat: no-repeat; 
}
<div id = "image">Hover over an image below to display here</div>

<img class = "preview" alt = "Beautiful kitten"
src = "https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg"
onmouseover = "update(this)"
 onmouseout = "undo()"/>

<img class = "preview" alt = "Pretty Kitty" 
src = "https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg"
onmouseover = "update(this)" onmouseout = "undo()"/>

<img class = "preview" alt = "Baby cat"
src = "https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover = "update(this)" onmouseout = "undo()"/>

0

I just changed a little your JS function to update it with correct params. In order to implement an undo I figured out you might want to store the previous text shown before any onmouseover. Hope it helps!

function update(previewPic){
   console.log('onmouseover');
   const image = document.getElementById("image");
   image._oldText = image.innerHTML;
   image.style.backgroundImage = `url(${previewPic.src})`;
   image.innerHTML = previewPic.getAttribute("alt");
}

function undo(){
  console.log('onmouseout');
  const image = document.getElementById("image");
  image.style.backgroundImage = "";
  image.innerHTML = image._oldText;
}
<div id="image">Hover over an image below to display here</div>

<img class="preview" alt="Beautiful kitten" style="width:100px;"
src="https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg"
onmouseover="update(this)" onmouseout="undo()"/>

<img class="preview" alt="Baby cat" style="width:100px;"
src="https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover="update(this)" onmouseout="undo()"/>

0

Hopefully this will help

<style>
.preview {
  width: 50px;
  height: 50px;
}

#image {
  width: 100px;
  height: 50px
}
</style>

<div id="image">Hover over an image below to display here</div>

<img class="preview" alt="Beautiful kitten" src="https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg" onmouseover="update(this)" onmouseout="undo()" />

<img class="preview" alt="Pretty Kitty" src="https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg" onmouserover="update(this)" onmouseout="undo()" />

<img class="preview" alt="Baby cat" src="https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover="update(this)" onmouseout="undo()" />
<script>

  function update(previewPic) {
    let divWithIdImage = document.getElementById("image");
    divWithIdImage.style.backgroundImage = 'url(' + previewPic.src + ')';
    divWithIdImage.innerHTML = previewPic.alt;
  }


  function undo() {
    let divWithIdImage = document.getElementById("image");
    divWithIdImage.style.backgroundImage = "";
    divWithIdImage.innerHTML = 'Hover over an image below to display here'
  }

</script>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.