Image Hover Generator

610 views javascript
1

If I have 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 names 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?

answered question

1 Answer

11

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);
});

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories