Introduction:
Through this article you will get the knowledge of events. You can change the image background using some events. In this article you will see an example to change the image background.
What is Events?
Events are the actions that can be detected by JavaScript. Events are normally used in combination with functions, and the function will not be executed before the event occurs.
These are the following events in JavaScript.
- onload and onUnload
- onSubmit
- onFocus, onBlur and onChange
- onMouseOver and onMouseOut
In this article you will see the use of onMouseOver and onMouseOut events.
How to change image background using JavaScript?
To change the image background use a function within the <script> and </script> tags something like this:
<script type="text/javascript">
function imagechange(imgName)
{
document.body.background = eval(imgName + ".src");
}
</script>
Example to change Image background:
<html>
<head>
<title>Change_image_background</title>
<script type="text/javascript">
clear = new Image();
clear.src = "clear.jpg";
pic1 = new Image();
pic1.src = "image1.jpg"
pic2 = new Image();
pic2.src = "image2.jpg";
pic3 = new Image();
pic3.src = "bigcar.jpg";
function imagechange(imgName)
{
document.body.background = eval(imgName + ".src");
}
</script>
</head>
<body>
<div align=center>
<a href="image1.jpg" onMouseOver="imagechange('pic1');" onMouseOut="imagechange('clear');">
<img src="image1.jpg"height=70 width=70></a>
<a href="image2.jpg" onMouseOver="imagechange('pic2');" onMouseOut="imagechange('clear');">
<img src="image2.jpg"height=70 width=70></a>
<a href="bigcar.jpg" onMouseOver="imagechange('pic3');" onMouseOut="imagechange('clear');">
<img src="bigcar.jpg" height=70 width=70></a>
</div>
</body>
</html>
In this example you have to see the mouse events (like onMOuseOver and onMouseOut). onMouseOver event will be fire when you put the cursor over the image and onMOuseOut event will be fire when out the cursor from the image.
Output:
Figure 1: Output of the script.
If you put your cursor over the image then background will be change like this:
Figure 2: Image is appearing in the background.
Similarly other images will be appear when you put the mouse on those images.
When you remove the cursor from the image then background will we clear.
If you click on any image then that image will be open onto another page like this:
Figure 3: Second image is displaying onto another page.