ahlie94
ahlie94

Reputation: 171

Image Hover Generator

Let's say I have the following HTML code:

 <!doctype html>
<html lang="en">
<head>
  <title> Lab 6 - Task 1 </title>
  <meta charset="utf-8">

  <script src="imagechanger.js"></script>
  <style>
    div {
      width: 50%;
      margin: auto;
      text-align: center;
      font-family: sans-serif;
    }
    img { width: 300px; }
  </style>
</head>
<body>
  <div>
  <h1> Fernandel Faces </h1>
<img src="face1.png" id="faces">

  <p> Ask a question! </P>
  <p> Move Mouse Over Fernandel for a Response </p>
  </div>
</body>
</html>

and I have 4 files named face1.png, face2.png, face3.png and face4.png, how would I write my Javascript so that when my mouse hovers over the initial image every time, it randomly changes to one of the 4 images?

ANSWER:

window.onload=function(){

var images = ["face1.png", "face2.png", "face3.png", "face4.png"];

document.getElementById("faces").addEventListener("mouseover", function(event) {
    var random = images[Math.floor(Math.random() * images.length)];
    event.target.setAttribute("src", random);
});
}

Upvotes: 0

Views: 285

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44115

Use this JavaScript:

var images = ["face1.png", "face2.png", "face3.png", "face4.png"];

document.getElementById("faces").addEventListener("mouseover", function(event) {
    var random = images[Math.floor(Math.random() * images.length)];
    event.target.setAttribute("src", random);
});

Upvotes: 1

Related Questions