jQuery: sticky blog dates

In this post I'm going to show how to create sticky blog dates using jQuery and CSS. CSS will be used to display our dates in the correct position, while jQuery will provide the basic date formatting. My source of inspiration for this post is the Wordpress Lightword theme, though I made some minor changes to the date formatting. As always, let's start with our markup structure:

<div id="content">

 <div class="post">
 
  <h2>...</h2>
  <div class="post-date">June 2, 2011</div>
  
  <p>...</p>
   </div>
   
   <!--more posts-->
   
</div>

All dates must always appear on the top left corner of the post area, but outside the main content area. To accomplish this, we'll use contextual positioning by declaring our posts as relatively positioned and our dates as absolutely positioned:

#content {
 width: 50%;
 margin: 0 auto;
 background: #fff;
 border-radius: 15px;
 padding: 1em 0;
}

div.post {
 margin: 1em 0;
 width: 100%;
 position: relative;
}

div.post h2 {
 width: 80%;
 margin: 0 auto;
 font-size: 1.5em;
}

div.post p {
 width: 80%;
 margin: 0 auto 1em auto;
 line-height: 1.3;
}

div.post div.post-date {
 width: 79px;
 height: 80px;
 background: url(jquery-sticky-blog-dates/date.png) no-repeat;
 position: absolute;
 top: 0;
 left: -79px;
}

div.post div.post-date span.month-day {
 display: block;
 text-align: center;
 font-size: small;
 font-weight: bold;
 color: #fff;
 padding-top: 4px;
}

div.post div.post-date span.year {
 display: block;
 text-align: center;
 padding: 20px 0 0 0;
 font-size: 1.5em;
 color: #2c2c26;
}

The purpose of the last two CSS classes will be clear when we'll add jQuery. In fact, with jQuery we want to change the following date structure:

<div class="post-date">June 2, 2011</div>

into this:

<div class="post-date">

 <span class="month-day">Jun 2</span>
 <span class="year">2011</span>

</div>

Here's the jQuery code:

$(function() {

  $('div.post-date').each(function() {
  
    var $date = $(this);
    var text = $date.text();
    var parts = text.split(',');
    var months = parts[0].split(/\s/);
    var month = months[0].substring(0, 3);
    var day = months[1];
    
    var monthDay = '<span class="month-day">' +
                    month + ' ' + day + '</span>';
    var year = '<span class="year">' 
                + parts[1] + '</span>';
    
    $date.html(monthDay + year);
  
  
  
  });


});

We've first split the text content of each date wrapper into two main chunks using the comma as separator. Then we've split in turn the first item of the newly created array using a space as separator. With the aid of the substring() function we've extracted only the very first three letters of each month name. 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.