jQuery

jQuery Image Rollover Effect Example

If you have wondered if it is possible to create a  rollover for an image using jQuery, then the answer to it is: “Yes”! In this article by using a simple example, I am going to show you how to use  jQuery to create Image Rollover effect.

Example of Image Roll Over Effect Using jQuery

Let’s look at the demo first:

Before Rollover:

After Rollover:

For the sake of example, let’s assume that you have a main “container” div that contains both the images i.e the image that needs to be shown by default and the roll over image as well.

Example: Here is the complete source code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Image Rollover</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
.container {
width: 300px;
}
</style>
</head>

<body>

<div class="container">
<img src="1.jpg" width="300" height="300" class="img_default">
<img src="2.jpg" width="300" height="300" class="img_rollover">
</div>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){

$('.img_rollover', $(this)).hide();

$('.container').hover(
function() {
$('.img_default', $(this)).hide();
$('.img_rollover', $(this)).show();
},
function() {
$('.img_default', $(this)).show();
$('.img_rollover', $(this)).hide();
}
);

});
</script>
</body>
</html>
Simple, isn’t it?

Do you know of any other ways to make Image rollover effect using jQuery? Feel free to suggest by commenting below.

P.S:  If you would like to find out how to achieve Image Rollover effect using CSS, then read my article on CSS Image Rollover with Example

3 Comments on jQuery Image Rollover Effect Example

  1. 1

    very nice example..good one..

  2. 2

    Hi Robert –

    I’m not sure why it’s necessary to include the jQuery function. The css takes care of the rollovers and adding or removing the jQuery function has no effect. Just curious.

    Thanks!

    • 3

      Hi Steve,
      That’s actually a very good point. My main intent was to show how to achieve the rollover effect just by using jQuery but it looks like I combined 2 examples into one & posted the same when writing this article. As such, I have now updated the code so that when the rollover effect is controlled purely via jQuery. I will be writing another article on how to achieve the same rollover effect using pure CSS soon.

      Thanks for pointing it out. It helped me eliminate confusion.

      Regards,
      Robert

Share your thoughts, comment below now!

*

*