A Kaidez Article

TUTORIAL: A Simple, Effective jQuery Image Rollover

TOPIC: Tutorials

I used the following code to create the image rollovers for the recent Almay project I worked on.

Truthfully, I wasn’t going to post this: I found it on another site and felt that re-posting it here would be claiming it as my own creation. But I found quite a few other sites using the exact same script, so I’m not the only one re-posting it. Plus, this rollover code works…well I might add. It doesn’t use CSS, making it much more cross-browser compliant; it’s not as buggy as some other JavaScript rollover code I’ve encountered, and it gets the job done with very little code.

I’m viewing all those other re-posts as an endorsement of how almost-perfect this code is. Here’s my endorsement:

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>A Simple jQuery Image Rollover</title>

<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$("img.rollover").hover(
function() { this.src = this.src.replace("_off", "_on");
},
function() { this.src = this.src.replace("_on", "_off");
});
});
</script>

</head>
<body> 

<a href="#"><img src="imageOne_off.png" class="rollover" /></a>
<br />
<a href="#"><img src="imageTwo_off.png" class="rollover" /></a>

</body>
</html>

First, make sure that you create your rollover images. Each individual rollover needs two images attached to it: one named ‘yourFilename_off.gif’ and the other named ‘yourFilename_on.gif’. As long as these images are of the same file type, it doesn’t matter what file type it is. GIF, JPEG, PNG…it doesn’t matter. For this example, I have four images that will be used in two rollovers:

  • ‘imageOne_off.png’
  • ‘imageOne_on.png’
  • ‘imageTwo_off.png’
  • ‘imageTwo_off.png’

And now the code breakdown…

We make sure to embed the jQuery library into our web page grabbing the one stored over at jquery.com:

<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>

Next, we tell jQuery that every time an image tag with a class name of “rollover” gets moused over, it should simultaneously perform two tasks:

  • it should see if the image contains the word “_off” in the filename…if it does, replace it with “_on” which will force the “_on” version of image to load.
     
  • it should see if the image contains the word “_on” in the filename…if it does, replace it with “_off” which will force the “_off” version of image to load.
<script type="text/javascript">
$(document).ready(function() {
$("img.rollover").hover(
function() { this.src = this.src.replace("_off", "_on");
},
function() { this.src = this.src.replace("_on", "_off");
});
});
</script>

And from here, we just place the images on the web page, making sure that they have a class name of “rollover”:


<br />

That’s it!!! The best rollover code I’ve ever used!!!

One more jQuery-related post, then it’s time to discuss HTML5 video!!!!!!

 
 
 

41 Responses to TUTORIAL: A Simple, Effective jQuery Image Rollover

  1. BerklieNo Gravatar says:

    Very nice… thanks so much!

  2. kaidezNo Gravatar says:

    Thanx much, Berklie! Let me know if I wasn’t clear on anything

  3. ValNo Gravatar says:

    Very nice. Thanks!! It was very clear and quick to implement. I’ve been looking for something like this.

  4. kaidezNo Gravatar says:

    Hi Val. Thanks for stopping by as well as your kind words! All of it is greatly appreciated.

  5. RyanNo Gravatar says:

    Thanks for the script! It seems straightforward, and I was looking for something like this for a project I’m currently working on. Perhaps in the future, you could include a brief demo?

  6. kaidezNo Gravatar says:

    Hi Ryan. That’s a very fair request…will try to get this up as soon as I can.

  7. BaretNo Gravatar says:

    Hi,

    Thanks for the code. However, I can’t get it to work. I did everything exactly as described above, but when my mouse hovers over the image it does not change. Any ideas?

    Maybe a conflict with other scripts?

  8. kaidezNo Gravatar says:

    Hi Baret. I’m sorry to hear that you’re having trouble. Would you mind posting your code?

    If you are using another JavaScript library (such as Dojo or script.aculo.us), that definitely could cause conflicts with other scripts. But let’s look at your code first before we say that’s they issue.

  9. BaretNo Gravatar says:

    Hi Kaidez,

    Thanks for your quick reply. I’m only using Jquery.

    Code:

    Title

    jQuery.noConflict();

    (function($) {

    $(document).ready(function() {
    //code here that depends on the document being fully loaded
    });

    })(jQuery);

    $(document).ready(function() {
    $(“img.rollover”).hover(
    function() { this.src = this.src.replace(“_off”, “_on”);
    },
    function() { this.src = this.src.replace(“_on”, “_off”);
    });
    });

    //////// content //////



    jQuery(function(){
    jQuery(“.carousel”).jCarouselLite({
    btnNext: “.next-button”,
    btnPrev: “.prev-button”
    });
    });

    Thanks in advance!

  10. kaidezNo Gravatar says:

    Hi Baret. Thanx much!

    Based on the Pastebin link, I’m going to suggest that you just change the top jQuery function to look like either like this:


    <script type="text/javascript">
    $.noConflict();
    jQuery(document).ready(function($) {
    $("img.rollover").hover(
    function() { this.src = this.src.replace("_off", "_on");
    },
    function() { this.src = this.src.replace("_on", "_off");
    });
    });
    </script>

    Or like this:


    <script type="text/javascript">
    $.noConflict();
    jQuery(document).ready(function($) {
    $("img.rollover").hover(
    function() { this.src = this.src.replace("_off", "_on");
    },
    function() { this.src = this.src.replace("_on", "_off");
    });
    });
    </script>

    What I did was add jQuery’s $.noConflict(); function to my code and also changed the first line. Here’s the explanation why and please feel free to ask me clarify things:

    WordPress versions 3.1 or lower treated the major JavaScript libraries in various ways.

    Almost all of them automatically added jQuery
    Many of them added other JS libraries, like prototype or script.aculo.us

    The issue is the ‘$’. Almost all the big JS libraries use it in their code and the end result of this is: when all them are on the same web page, it might cause errors. Even if you don’t actually use them, errors may still come up.

    jQuery addressed this problem by creating the ‘$.noConflict();’ function, which prevents the bugs. It’s basically saying “HEY ALL YOU OTHER JS LIBRARIES, LEAVE MY ‘$’ ALONE SO I CAN DO MY JOB!!!”

    In your case you have both the prototype or script.aculo.us JS libraries installed on your page so $.noConflict() may be needed here. An example of this code in action is the empty function that starts on line 14 of the PasteBin page.

    Take note: older versions of WordPress don’t treat custom-installed jQuery so you may have issues. Let me know if these issues pop up and we’ll keep trying.

    HTH,
    kaidez

  11. kaidezNo Gravatar says:

    Sorry…made a boo-boo. Code option #2 should actually look like this:


    jQuery.noConflict();

    (function($) {

    $(document).ready(function() {
    $("img.rollover").hover(
    function() { this.src = this.src.replace("_off", "_on");
    },
    function() { this.src = this.src.replace("_on", "_off");
    });
    });

    })(jQuery);

  12. BaretNo Gravatar says:

    Thanks! Works perfectly.

    However, not on all pages. :(

    Code: http://pastebin.com/GUmyFGeN

    Thanks again!

  13. kaidezNo Gravatar says:

    Hey Baret. For the the button image tags on lines 47 and 48 of the Pastebin page, try making their image references absolute instead of relative. The WordPress directory structure is funky that way.

    Most likely, the reference will have “wp-content/themes/” in it somewhere.

  14. BaretNo Gravatar says:

    Thanks for your reply, but I don’t use WordPress.
    I modified a template and made my site in DreamWeaver. I just uploaded all .html files to the root of public_html. The off images show up, but do not change to on when hovering over them. It does work, however, on other pages.

    You can take a look here: http://www.btdesign.nl (homepage and FAQ do not work).

  15. kaidezNo Gravatar says:

    Hey Barrett. Thanks for the page link!

    I was able to test your site code in FireBug, rolled over the three social networking links at the bottom. In this case, the $.noConflict() function is not needed on either the homepage or FAQ since neither one has Prototype or script.aculo.us. If you are coding within the WordPress framework, there will certainly be times when you do need it, depending on the situation. But as you’re developing outside of WP, you can do without it in this case.

    For each of these two pages, please use the original code that I used in the tutorial, which doesn’t implement “$.noConflict().”

    Also, the rollover isn’t working on the Contact page: that can be fixed by adding the function to the page. Since that page also doesn’t include either Prototype or script.aculo.us, using the function without $.noConflict() should do it.

  16. BaretNo Gravatar says:

    Thank you very much! I really appreciate your fast replies and clear instructions. Thanks again!

  17. kaidezNo Gravatar says:

    You’re welcome! happy to help!

  18. excellent, thanks a lot. any simple way to have it pre-load the rollover image?

  19. kaidezNo Gravatar says:

    Hey Chris. Thanks for stopping by and your kind words!

    Alex Dickerson has made a image preloading JQ script that I’be heard thru the grapevine is good. Check out at:

    https://github.com/alexanderdickson/waitForImages

  20. AlexNo Gravatar says:

    Just a note, my name is “Alex Dickson” not “Dickerson” :P

    Glad you like the plugin :)

  21. RosemaryNo Gravatar says:

    This script is great!

    Just one thing though, is it possible so that once it’s been hovered, it goes back to the original image? So the image is only active when the link is hovered and goes back to the original image once it isn’t?

  22. Thanks – nice and clean

  23. BenNo Gravatar says:

    This is fantastic…thanks!

  24. WilliamNo Gravatar says:

    This plugin is great, but how would I go about adding in a fade-in and fade-out effect when hovering?

  25. WilliamNo Gravatar says:

    This tutorial is great, but how would I go about adding in a fade-in and fade-out effect when hovering?

  26. I love this solution! now is there something i can add to this script so that it will preload every “_on” image that has the class=”rollover”?? That would be bulletproof.
    Thanks for your generosity and genius.

  27. kaidezNo Gravatar says:

    Hi Levi…thanks for the kind words!

    As far as preloading goes, you may want to preload the “_off” images as well as the “_on” ones for better performance overall. Off the top of my head, I can think of two ways to do this:

    -the new skool way: grab Alex Dickson’s waitForImages preload plugin for jQuery at https://github.com/alexanderdickson/waitForImages.

    -the old skool way: use the Image object in JavaScript. If you want to preload an image called ‘levi.png’ then this code would look like..


    var img = new Image();
    img.src = "levi.png";

    HTH,
    kaidez

  28. NageshNo Gravatar says:

    Very nice. Thanks!!

  29. NicoleNo Gravatar says:

    It works! Have been searching for this functionality for a while. Thank you!

  30. Nice, thanks for posting.
    Bill

  31. KatNo Gravatar says:

    Fantastic! Thank you so much.

  32. kuhandossNo Gravatar says:

    Thanks Man…

  33. EmproNo Gravatar says:

    Thanks for this.

    I created a simple script to do a preload for my purposes, but it is fairly generic – I simply wanted to preload the rollover _on images . Haven’t tested on all browsers, etc. yet, but it did work in latest versions of Chrome, Firefox and IE for me.

    $(“img.rollover”).each(function () {
    (new Image()).src = this.src.replace(“_off”, “_on”);
    });

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">