Image Hover Generator

623 views javascript

If I have HTML code:

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

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

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

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


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)];"src", random);

posted this

Have an answer?


Please login first before posting an answer.