jQuery: inserting separators in a menu

Web developers are generally accustomed to use pipes (|) as separators between the items of a navigation menu. Generally speaking, this approach is due to the fact that using CSS borders doesn't allow for a complete control over these vertical bars, because there's no CSS property that controls the vertical height of a border. More specifically, a CSS border will be always as tall as the overall height of its box. Further, in order to make some room for the inner contents of a box, the only property you can use is actually the padding property.

For that reasons, most developers use a pipe as a separator. However, the major drawback to this approach is that you have to manually insert additional markup to control these newly inserted separator, something like:

<span class="separator">|</span>

This kind of markup is non-semantical so it's better to avoid it. Instead, let's use jQuery to accomplish this task. To start with, here's a basic navigation menu:

<ul id="navigation">
 
 <li><a href="#">Home</a></li>
 <li><a href="#">Articles</a></li>
 <li><a href="#">About</a></li>
 <li><a href="#">Contact</a></li>
 
</ul>

with some styles attached to it:

#navigation {
    margin: 0;
 padding: 0 0 0 0.5em;
 list-style: none;
 height: 2em;
 font-size: 1.3em;
 background: #777;
 color: #fff;
}

#navigation li {
    margin-right: 0.5em;
 height: 100%;
 float: left;
}

#navigation a {
    float: left;
 height: 100%;
 line-height: 2;
 padding: 0 0.5em;
 color: #fff;
 font-weight: bold;
 text-decoration: none;
}

#navigation a:hover {
    background: #aaa;
}

#navigation span.separator {

    float: left;
    height: 100%;
    padding-left: 4px;
    line-height: 2em;

}

As you can see, we've already provided the required styles for our separator. Now it's time to insert them:

$(document).ready(function() {
  
  $('#navigation li').not('#navigation li:last-child').each(function() {
   
   var separator = $('<span class="separator"></span>').text('|');
   
   separator.appendTo($(this));
   
  });
  
  
  
 
});

All our menu items will have a separator, except the last one. You can see the result below.

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.