How to Make a JavaScript Image Rollover
In the world of web development, image rollovers are a popular technique for enhancing user experience. They are interactive images that change appearance when the mouse cursor rolls over them. This guide will walk you through the process of creating a JavaScript image rollover, step by step.
1.Prepare your images
Before starting with the code, you will need two different images – one for the default state and another for the rollover state. Ideally, both images should be of the same size and dimensions. Save these images in your project folder.
2.Set up your HTML file
Create an HTML file and add the following structure:
“`html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Image Rollover</title>
<script src=”rollover.js”></script>
</head>
<body>
<img src=”default-image.jpg” alt=”Image rollover” id=”image”>
</body>
</html>
“`
Replace “default-image.jpg” with your default image filename. Also, notice that we included a script tag to link an external JavaScript file called “rollover.js.” We will create this file in the next step.
3.Create the JavaScript file
In your project folder, create a new file named “rollover.js”. Inside this file, add the following code:
“`javascript
function mouseoverEvent() {
document.getElementById(“image”).src = “hover-image.jpg”;
}
function mouseoutEvent() {
document.getElementById(“image”).src = “default-image.jpg”;
}
window.onload = function() {
var imageElement = document.getElementById(“image”);
imageElement.onmouseover = mouseoverEvent;
imageElement.onmouseout = mouseoutEvent;
}
“`
Replace “hover-image.jpg” with your rollover image filename and replace “default-image.jpg” with your default image’s filename. This script defines two functions, “mouseoverEvent()” and “mouseoutEvent()”. The former function changes the image source to the rollover image when a mouseover event occurs, whereas the latter reverts it back to the original image on a mouseout event.
The “window.onload” section ensures that these functions are assigned to their respective events only after the page has completely loaded.
4.Test your image rollover
Save all the changes you’ve made so far. Open your HTML file in a web browser and hover your mouse pointer over your image. If everything is set up correctly, you should see the image change upon hovering and revert back to its original appearance when moving your cursor away from it.
That’s it! You’ve successfully created a JavaScript image rollover. You can now apply this technique to add interactivity to images on your website, enhancing user engagement and overall experience.