Computer >> Computer tutorials >  >> Programming >> Javascript

How can I show image rollover with a mouse event in JavaScript?


To show image rollover with a mouse event, you can try to run the following code −

Example

<html>
   <head>
      <title>Rollover with a Mouse Event</title>
      <script>
         <!--
            if(document.images) {
               var image1 = new Image(); // Preload an image
               image1.src = "/images/html.gif";
               var image2 = new Image(); // Preload second image
               image2.src = "/images/http.gif";
            }
         //-->
      </script>
   </head>
   <body>
      <p>Move your mouse over the image to see the result</p>

      <a href = "#" onMouseOver = "document.myImage.src = image2.src;" onMouseOut = "document.myImage.src = image1.src;">
         <img name = "myImage" src = "/images/html.gif" />
      </a>
   </body>
</html>

Let's see what we have used in the above example to automate animation −

  • At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed.
  • The Image() constructor creates and preloads a new image object called image1.
  • The src property is assigned the name of the external image file called /images/html.gif.
  • Similarly, we have created an image2 object and assigned /images/http.gif in this object.
  • The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
  • The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image).