Sunday, September 05, 2010

Fading Image Hover Pop-ups with jQuery

I wanted to put a number of small camera icons on a page and have the images pop up with a nice "fade" effect when you hover over them. At first I looked around for a jQuery plugin for this. I didn't really find any that did exactly what I wanted, then I decided to just code it. Turns out this is so simple it doesn't really need a plugin at all. Just two lines of jQuery code does the trick.

First, here's the markup I used:
<div class="imghover"> 
  <a href="photos/photo1.jpg">
     <img src="images/camera.gif">
     <div>
         <img src="photos/photo1.jpg" alt="Image I want to pop up.">
     </div>
  </a>
</div>

And here's the CSS:

.imghover {
  position: relative;
  }

.imghover div {
  position: absolute;
  right: 0;
  bottom: 0;
  border: 1px dotted red;
  padding: 8px;
  display: none;
  background: pink;
  }

The key things here are the absolute positioning of the child div, and display: none. In my layout it made sense to align the bottom right corner of the pop up image with the bottom right corner of the camera icon (thus, right: 0; bottom: 0;). So, the positioning, border, padding, and background color you can change to suite your needs.

Finally, as promised, here's the two line jQuery script to bring it to life:
$(".imghover").hover(function() { $(this).children("div").fadeIn(); },
                       function() { $(this).children("div").fadeOut() });

The jQuery hover function takes two parameters, both of which are function callbacks. The first one is called when your mouse moves over the target (i.e. the "mouse over" event), and the second one is called when your mouse moves off the target (i.e. the "mouse out" event). In this case the target is any div on the page with class="imghover". In each function we find the one and only child div element (based on the markup above). For the first function we call fadeIn() to make the image appear, and likewise on the second function we fade it out to make it disappear.

One nice thing to note about this is that in order to get the image to pop up you have to hover over a small area - namely the camera icon. But once the image pops up, you can move your mouse anywhere over the popped up image and it stays in place. Only when you go outside the bounds of the image does jQuery perform the "mouse out" callback and cause us to fade it out. That's because the image itself is a child of the div element we called hover() on, so jQuery will not fire the "mouse out" callback until we move off of the image.

1 comments:

tpauly said...

This sounds like what I want to do but I can't make it work.
http://www.theablebaker.com/draft/jq-popup.html
http://www.theablebaker.com/js/jquery.popup.js
Am I doing something wrong?
Thanks.

Post a Comment

Note: Only a member of this blog may post a comment.