Aug
05
2009

Creating a Mouseover Fade Effect with jQuery

by   |  Posted in Tutorials  |  200 comments

My last little jQuery tutorial was an alternative to using CSS to create an image change on a mouseover. Now I want to take that one step further and add a fade effect. For my example, I am going to make a black and white image fade into a color image. To achieve this effect I am going to introduce the animate function. There are tons of possibilities in regards to jQuery’s animate function, but for this tutorial, I’m going to keep it simple by just using it to do one thing.

First things first, download jQuery. Grab the Production minified version off of their site. Next, get two images. I used the following.

cbavota-bwcbavota


Add the jQuery script between your head tags.

<script type='text/javascript' src='http://yoursite.com/jquery.js'></script>

Here is the function.

<script type='text/javascript'>
$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});
 
});
</script>

Here is the CSS.

<style>
 
div.fadehover {
	position: relative;
	}
 
img.a {
	position: absolute;
	left: 0;
	top: 0;
	z-index: 10;
        }
 
img.b {
	position: absolute;
	left: 0;
	top: 0;
	}
 
</style>

And here is the body code.

<div class="fadehover">
<img src="cbavota-bw.jpg" alt="" class="a" />
<img src="cbavota.jpg" alt="" class="b" />
</div>

All together you got something that looks like this.

<!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 Hover Effect</title>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
 
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});
 
});
</script>
<style>
div.fadehover {
	position: relative;
	}
 
img.a {
	position: absolute;
	left: 0;
	top: 0;
        z-index: 10;
	}
 
img.b {
	position: absolute;
	left: 0;
	top: 0;
	}
</style>
</head>
 
<body>
<div class="fadehover">
<img src="cbavota-bw.jpg" alt="" class="a" />
<img src="cbavota.jpg" alt="" class="b" />
</div>
</body>
</html>

Test it out below:

NOTE: If you are using jQuery with WordPress, you need to replace all the dollar signs ($) with the word jQuery due to other Javascript libraries that use the dollar sign.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , , , , , , , , ,

Short URL: http://bit.ly/bETRnX

Discussion 200 Comments

  1. freezie on August 6, 2009 at 9:26 am

    Very cool. Thanks for the tut.

    • Petra on February 1, 2011 at 3:19 pm

      I really would like to say thank you too, I’m defintily going to use this :)

    • mua sam vui on April 4, 2011 at 7:19 am

      is this like this page when hover mouse the code auto explane ???

  2. vestarnoob on August 6, 2009 at 10:07 pm

    I have been using javascript for years and I just find jquery so easy to use. All of its extra features really help make a website more interactive.

  3. Banner design guy on August 24, 2009 at 6:58 am

    I’m looking for something more simple only for fading background colors… but this is really nice, too :) 10x

    • Lee Wilson on September 27, 2009 at 8:40 am

      I too am trying to find out how to fade background colours.

  4. Umair on August 24, 2009 at 9:39 pm

    Awesome! Its a nice collection in my designing knowledge. jQuery is replacing flash animations slowly!

  5. vkline on September 6, 2009 at 8:49 am

    Thank you for the post. :)

  6. Arash on September 14, 2009 at 5:12 am

    Thank you for your great tutorial. Just 2 points.

    In your body code you forgot a closing div.
    In IE (7 and 8) the fade effect created a black border around transparent (24bit) png files. Perhaps you can add a small code to make that go away without having to use .gif or a 8bit .png.

    That would make a great code into an excellent code.

    :)

    • c.bavota on September 14, 2009 at 6:51 am

      Thanks for letting me know. I added the missing div. Let me look into that black border issue.

    • rotagila on May 19, 2010 at 1:30 pm

      You can get rid of the black border issue in IE by setting a background-color of the image. I had those grey borders even on jpgs, setting the background-color worked for me.

  7. Gaya on September 23, 2009 at 11:57 am

    Nice piece of code.
    Try putting “.stop()” before “.animate()” to prevent the animation from getting in a loop.
    Again: awesome stuff.

    • acepek on May 3, 2010 at 9:23 pm

      Good tip. Adding the stop like so:

      .stop().animate({“opacity”: “0″}, “slow”);

      keeps the effect from repeating if the mouse passes over it multiple times.

    • Jepser on February 13, 2011 at 11:08 am

      Wrong @acepek you have to add stop(true, true) in order to prevent a loop. stop(param, param) are default false,false.

  8. manojit on September 28, 2009 at 8:32 am

    hi,

    i believe you have explained well enough for a person using web language.
    well i am merely a motion graphic designer… and i am trying to make my website through wordpress… and i like the idea of doing it myself.. its fairly a simple one..
    i have a page where i have icons and links on them which enables a video to play on a shadowbox.(through a plugin)
    i now need this effect on mouseover on the icons…
    so i need to know where should i need to paste this codes (well to begin with there are plenty of them :)
    would you please be kind enough to explain it w.r.t wordpress codes. i would be grateful

    ragards
    manojit

  9. js on October 6, 2009 at 4:00 pm

    This is fabulous! I’ve been trying to figure out a way to animate a before and after effect for multiple images and this works perfectly. Thanks for the great tutorial!

    • Little Genius on December 14, 2010 at 3:31 am

      Hi,

      I want to make more than 1 thumbnail with this effect. I was trying to do this but I don’t know how. Can someone please help me with the css to have this gallery with this effect? This is my project and here I want to apply your work => ww.iulianfest.ro/decoratiuni-sala

      Thanks!

  10. Steve on October 9, 2009 at 3:19 pm

    GREAT!! This is almost exactly what I need.

    What I want to do is to have multiple rows and columns of thumbnails that are black and white which fade to color as you mouseover each of them… is there a way to modify the code so that the color image will always be directly under the black and white image without setting the position of the black and white image?

    Thanks,
    Steve

    • c.bavota on October 13, 2009 at 12:28 pm

      If you want an image to appear below another image you will always have to set the position or else they will appear next to each other.

  11. mojitopl on November 1, 2009 at 5:47 pm

    Did anyone solved tha god damn IE black border on animated transparent png-s (24bits)!? Thanks a loooooot for any clue.

  12. Neil on November 2, 2009 at 7:50 am

    Hi.
    This bit of code is great. I’m attempting to use the fade as a background behind some image and text divs (set to a z-index higher than the fadehover) but every time i roll over the image or text the fade changes back to it’s original state.

    http://www.diluterecordings.com/2009/

    Is there a fix for this so that the box stays highlighted while the mouse is over any area of the box?
    Thanks,
    neil

    • c.bavota on November 4, 2009 at 2:15 pm

      Make sure you have added the .stop() before the .animate() function.

  13. acid on November 12, 2009 at 1:45 pm

    what if I want to add more colors (same image other color) and make each mouseover show another color in an order (not randomized)? how would that work?

  14. Harpreet on November 26, 2009 at 5:46 am

    Hi…

    can i use this jquery mouse over effect with lightbox. I want the same effect and when i click on the image it should open it in lightbox.

    But it’s not working…please help me asap

    Thanks in advance

  15. Rawkid on December 27, 2009 at 1:04 am

    Hi and thanks putting up this tutorial!

    First of all, i’m in no way a webdesigner/coder/programmer. I’m “messing around” with WordPress myself and doing what i can. The “official” site is being developed by a coder as we speak. Till then i wanted to run a WordPress site.

    Ontopic: I’ve applied your tutorial to my site and actually it worked right away. And being a no-coder as i said, i had a little party but to know minutes later the party was over…
    On this page of my site you can see it’s working:
    http://www.rawkidrocks.com/props

    On this page however you can see i’m having some issues:
    http://www.rawkidrocks.com/dummy

    As you can see, i’m trying to put several images underneath eachother, but they are overlapping.
    I’m guessing it has nothing to do with your css or jquery codes, but i hope you don’t mind asking you anyway. My guess is there’s something wrong with my styling or. So. Could you please have a look at this? I really hope you can help me out here.

    Regards,

    Johnny

    • c.bavota on December 28, 2009 at 10:42 am

      I would suggest settings the width and the height in your CSS so that each fadehover div does not overlap the other.

    • Rawkid on December 28, 2009 at 12:33 pm

      Thanks! I feel so stupid, knowing now it was something that “simple”. But then again, i don’t know anything about coding. Thanks again and keep up the great job!

      Johnny

  16. srk289 on January 8, 2010 at 2:51 am

    Hi I tried different fixes for the IE black border issue but it didnt work.. Could you please post your possible solution

  17. Rodger on January 31, 2010 at 7:04 am

    I encountered a problem with your code, if I move the mouse over and away from the element repeatedly and quickly it will continue blinking for about 10secs to come after you have stopped moving the mouse. is there a fix for this?

    • c.bavota on January 31, 2010 at 9:26 am

      It wasn’t with the code, it was with the demo. I just forgot to update the demo code with .stop().

  18. kevin lofthouse on February 12, 2010 at 6:36 pm

    nice, I produced a similar effect with fadeTo, placing one image on top of another with absolute positioning. Yours seems alot easier then mine. good work :)

    http://www.iamkreative.co.uk/blog/design/fading-image-switch-jquery/

  19. Medi (051495) on February 15, 2010 at 9:35 pm

    THANK YOU!!!!!!!! You’ve helped me so!!! lol

  20. Harry on February 20, 2010 at 5:24 pm

    Hi, excellent and simple script.

    Had no problem using your example here to fade between pictures, but am having trouble adding a delay before the fade out. Is there a way of doing this?

    I understand that jquery 1.4+ has a delay function, but I can’t figure out how to integrate it here.

    Thanks again for the code :)

    • c.bavota on February 22, 2010 at 1:59 pm

      I still haven’t played around with 1.4 but as soon as I do I will let you know.

  21. Maximilian on February 28, 2010 at 11:30 am

    Hey and thank you very much for this script, it is really awesome!
    I have a problem and a question though, I’m building my new website and look what happens: http://www.avantgande.com/eyedr18/ I have tried to make this work with one image so far as a test (the girl with the dark hair with the read more tag) and while the fading part works great, the image is suddenly not at the right place anymore, and I really can’t tell what went wrong, my code looks clean..

    Also, I have lost Lightbox functionality here, is that possible?

    Thanks!
    Mx

    • Maximilian on February 28, 2010 at 1:07 pm

      Okay, in some weird way I managed to fix the first problem.. Now how about Lightbox integration? :)


      </div

      this is how my code looks like now, but obviously no result..

    • Maximilian on February 28, 2010 at 1:32 pm
       
              <a href="images/image-1.jpg">
       
       
              </a>
    • Maximilian on February 28, 2010 at 1:32 pm

      Okay the code is not showing up nicely at all.. :)

    • c.bavota on March 1, 2010 at 2:02 pm

      Paste your code between <pre> tags like indicated in the instructions below.

      But I am not too familiar with Lightbox so I don’t know if I can help you out.

  22. danie ocean on February 28, 2010 at 12:53 pm

    Can you do above example without absolute position tag?

    The site elements get misplaced while switching between bigger and smaller screens.

    • c.bavota on March 1, 2010 at 2:01 pm

      You can’t do it without absolute positions because the elements need to sit on top of one another.

  23. Maximilian on March 2, 2010 at 2:36 pm

    Hey I tried that but clearly it did not work.

    But here is where I am now: http://www.avantgande.com/eyedr18/
    The buttons underneath the first Flash banner are finally positioned in the right place, but at the very bottom of the screen is another line of thumbnail-buttons, that are now up too high (they should be on the black bar underneath).. But whenever I try to change a series of buttons, the other line also shifts because of that absolute tag I believe.. Anything I can do about this?

    Mx

    • Maximilian on March 3, 2010 at 7:19 am

      Ok I was able to solve my problem, just worked with more relative tags and now everything is fixed, except the Lightbox problem. Here goes my code again, trying with pre tags:

              <a href="images/image-1.jpg">
       
       
              </a>
    • Maximilian on March 3, 2010 at 7:20 am

      Damn it, same result and used the pre-tags. You can check it in my source code if you want to, it’s plain html.

      Mx

    • c.bavota on March 3, 2010 at 10:33 am

      It seems to be fine. I guess you figured it out.

      Just to let you know, you can use this for your jQuery instead of what you have:

      $("img.a, img.c, img.e").hover(
      function() {
      $(this).stop().animate({"opacity": "0"}, "slow");
      },
      function() {
      $(this).stop().animate({"opacity": "1"}, "slow");
      });

      Cuts down on the code and works the same.

    • Maximilian on March 4, 2010 at 5:07 pm

      Thanks! I did figure it out. :) Thanks for the tip on how to shorten it.

      Do you have any idea on how to get the lightbox feature back up?

    • c.bavota on March 6, 2010 at 10:55 am

      I don’t really use Lightbox so I am not too clear on what the problem might be.

  24. hugo on March 3, 2010 at 4:48 am

    hey.
    you are full of helpful tips and tricks. alas i require additional help. after much fighting i finally got the fade to work. problem is that it only fades to the different image once and then leaves it there. as you can see:
    http://www.blamethesky.com/site2.html

    assistance would be super.

    • Maximilian on March 4, 2010 at 9:17 pm

      Sure you copied the code completely right? Changed the jquery?

  25. Lau on March 5, 2010 at 4:43 pm

    This is just what I was looking for, and it’s really easy! Thank you for sharing!
    But i’m stucked with a little problem: could it be that it doesn’t work inside a php include? I run it separately and works just fine, but when I separate everything to fit the modules it just won’t make the fade effect.
    I checked and triple checked everything, and all seems to be correct.
    Did this happen to anyone else?

    • Lau on March 5, 2010 at 5:23 pm

      Never mind, already fixed it. I had to call Jquery again, it was so stupid ¬_¬
      Thank you for the amazing tutorial!