jQuery: dynamic image overlay

In this post I'm going to show you how to create a dynamic image overlay with jQuery. When a user moves his/her mouse on the image, the overlay is displayed. Then, when the mouse leaves the image area, the overlay is hidden. And so on. We start with a simple image gallery like this:

<ul id="gallery">
        <img src="http://dev.css-zibaldone.com/onwebdev/post/star-rating/1.jpg" alt="" />
        <p>Lorem ipsum dolor sit amet.</p>
    <!-- more items -->

The paragraph needs to be absolutely positioned and hidden with CSS, like so:

#gallery {
    margin: 0 auto;
    padding: 2em 0;
    width: 70%;
    height: 100%;
    overflow: hidden;
    list-style: none;

#gallery li {
    float: left;
    height: 250px;
    margin-right: 0.5em;
    width: 32%;
    position: relative;

#gallery li img {
    display: block;
    height: 100%;
    width: 100%;
    cursor: pointer;

#gallery li p {
    width: 100%;
    height: 0px;
    background: silver;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
    text-align: center;
    font: small Arial, sans-serif;
    text-transform: uppercase;
    z-index: 1;
    margin: 0;

We've created a contextual positioning on each list item so that each item will be the positioning context of our paragraph. Now let's add jQuery:

$(document).ready(function() {
   $('#gallery li').each(function() {
       var $li = $(this);
       var $img = $li.find('img');
       $img.mouseover(function() {
            height: '100%',
            lineHeight: '250px',
            opacity: '0.7'
          }, 'slow');
       $img.mouseout(function() {
               height: 0,
               opacity: 0
           }, 'slow');

We use the animate() method to set the height and the opacity of our paragraph based on the presence of the mouse pointer on the image area. You can see a demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: dynamic image overlay”

Leave a Reply

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