jQuery: dynamic outlines

Outlines were first introduced in CSS several years ago to allow developers to create some visual effects without using borders. The outline property (and other similar properties) draws an outline around an element without affecting the box model. Since at the moment CSS3 transitions are not widely supported without using vendor extensions, jQuery remains an optimal alternative. To create this effect, we have to insert an element before our target element and then apply some styles to it. Then our element is hidden. It will be revealed and then hidden again using a jQuery effect, such as fadeIn() or fadeOut(). Consider the following markup:

<ul id="gallery">

 <li>
   <img src="1.jpg" alt="" />   
 </li>
 
 <!--more items-->
</ul>

To draw an outline on each image, we have to insert an empty element just before the image with jQuery, thus transforming our structure into this one:

<ul id="gallery">

 <li>
   <div></div>
   <img src="1.jpg" alt="" />   
 </li>
 
 <!--more items-->
</ul>

In other words, we want to change the following state:

into this:

We'll use CSS positioning to make both the empty element and the image appear in the correct place. Here are our styles:

#gallery {
 margin: 0 auto;
 width: 690px;
 padding: 0;
 list-style: none;
}

#gallery li {
 float: left;
 width: 230px;
 height: 200px;
 position: relative;
 cursor: pointer;
}

#gallery li div {
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;
 border: 2px solid #c60;
 display: none;
 box-shadow: 0 0 12px orange;
 border-radius: 10px;
}

#gallery li img {
 width: 200px;
 height: 150px;
 display: block;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -75px 0 0 -100px;
}

We've also applied a couple of CSS3 properties to our outline to make things a little bit more appealing. Now jQuery:

$(document).ready(function() {

  $('#gallery li').each(function() {
  
    var $li = $(this);
    var $img = $li.find('img');
    
    
    $('<div/>').insertBefore($img);
    var $div = $li.find('div');
    
    $li.hover(function() {
    
      $div.fadeIn('slow');    
    
    }, function() {
    
      $div.fadeOut('slow');    
    
    });
  
  });

});

You can see the demo below.

Demo

Live demo

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

Leave a Reply

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