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:
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 + '")';
document.getElementsByClassName
returns anHTMLCollection
; you needdocument.getElementsByClassName("preview")[0]
to get the first one.