School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!
 

Code Snippets

  

jQuery Source Code



Image rollovers with JQuery

This is a snippet for doing image rollovers with JQuery. Check "Instructions for what is needed

Submitted By: PsychoCoder
Actions:
Rating:
Views: 1,135

Language: jQuery

Last Modified: June 16, 2009
Instructions: 1) Need latest version of JQuery (http://jquery.com)
2) Place following code in file named rollovers.js
3) Each image you want the rollover affect on add class="rOver" to each tag
4) Each image's rollover image needs to end with _over. Ex home.png for normal home_over.png for the rollover image

Snippet


  1. //Code for rollovers
  2. IMG = {};
  3.      
  4. IMG.ImageRollover =
  5. {
  6.      init: function()
  7.      {
  8.         this.preload();
  9.        
  10.         $(".rOver").hover(
  11.            function()
  12.            {
  13.                 $(this).attr( 'src', IMG.ImageRollover.HoverImg($(this).attr('src')));
  14.            },
  15.            function()
  16.            {
  17.                 $(this).attr( 'src', IMG.ImageRollover.NormalImg($(this).attr('src')));
  18.            }
  19.         );
  20.      },
  21.      
  22.      preload: function()
  23.      {
  24.         $(window).bind('load', function()
  25.         {
  26.            $('.rOver').each( function(key, elm)
  27.            {
  28.                 $('<img>').attr('src', IMG.ImageRollover.HoverImg( $(this).attr('src')));
  29.            });
  30.         });
  31.      },
  32.      
  33.      HoverImg: function(src)
  34.      {
  35.         return src.substring(0, src.search(/(\.[a-z]+)/)) + '_over' + src.match(/(\.[a-z]+)/)[0];
  36.      },
  37.      NormalImg: function(src)
  38.      {
  39.         return src.replace(/_over/, '');
  40.      }
  41. };
  42.  
  43. //Place in HEAD section of document
  44. <script type="text/javascript">
  45.     $(document).ready( function()
  46.     {
  47.         IMG.ImageRollover.init();
  48.     });
  49. </script>
  50.  

Copy & Paste


Comments

moopet 2010-02-28 05:58:13

Why would you do this in javascript instead of CSS? I can see the benefit of preloading (just) but I don't understand why anyone would use JS to do :hover effects.

maffelu 2010-07-04 22:56:34

moopet: Not all browsers support :hover


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.