I created a webpage (index.html) which links to a JS file. I have coded 3 flags in the HTML document which were adjusted to about the same size. When I hover over a flag with the mouse, another image appears showing the map of the country you are hovering.
I’m trying to get it to where whenever you hover ONE of the flag images, not only should the image switch to the map, but it should also change the h1 tag to the name of the country.
My issue is when I mouse over and mouse out, it changes all three images at the same time and i cant figure out this h1 dilemma. Here is my code below. Any advice or tips I would appreciate thank you for your time.
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="scripts/flags.js" type="text/javascript"></script>
</head>
<body>
<h1>Countries and Flags</h1>
<img id= "img1" onmouseover="setNewImage()" onmouseout="setOldImage()
" src ="images/usa-flag.png" width="300">
<img id= "img2" onmouseover="setNewImage()" onmouseout="setOldImage()
" src ="images/canada-flag.png" width="300">
<img id= "img3" onmouseover="setNewImage()" onmouseout="setOldImage()
" src ="images/germany-flag.png" width="300">
</body>
</html>
flags.js
function setNewImage()
{
document.getElementById("img1").src ="images/USAMap.png";
document.getElementById("img2").src ="images/CanadaMap.png";
document.getElementById("img3").src ="images/GermanyMap.png";
}
function setOldImage()
{
document.getElementById("img1").src ="images/usa-flag.png";
document.getElementById("img2").src ="images/canada-flag.png";
document.getElementById("img3").src ="images/germany-flag.png";
}
I tried messing around with document.querySelector but ended up doing more harm than good. I know i have to separate the images somehow but I’m stuck at a wall
3
Answers
You have to create a function for each event, like this:
index.html
flags.js
Add
this
to listeners inindex.html
and use associative array in flags.js
this way you can add/remove flags as much as you like
To amend the previous answer, this will allow you to add more countries without having to change your JS.
You can store the data within the HTML img element.
Using the data attribute add the name and links to the map image and flag image.
Then using JS you initially loop through the img class to load the initial flag image (this is done via a window event listener to check for the page loading).
Then you loop through all the img class elements to add a mouseover and mouseout event, of which each set the
img.src
property to either thedata-flag
or thedata-map
attribute.Additionally, change the
innerHTML
of theh1
to the value of thedata-name
attribute