jQuery: inserting pullquotes

Inserting pullquotes is always a tedious task. We can automate this process by using jQuery and its DOM methods for creating and inserting new elements. Let's say that we have a series of paragraphs and we want a pullquote to appear just before each of them. Further, we also want to populate our pullquote with a portion of text taken from each paragraph. Here's how you can do with jQuery:

$(document).ready(function() {

  $('#content p').each(function() {
  
    var $p = $(this);
    var text = $p.text();
    
    var quote = text.substring(0, text.indexOf(','));
    
    $('<blockquote class="pullquote"/>')
    .text(quote).insertBefore($p);
  
  });

});

We extract a substring from the text content of each paragraph and we use it to populate our pullquote that will be later inserted into the DOM just before each paragraph. We need the following CSS styles to make it appear as we want:

#content blockquote.pullquote {
 margin: 0 0 0 0.3em;
 width: 7em;
 padding-left: 75px;
 background: url(quotes-left.png) no-repeat 0 0;
 float: right;
 clear: right;
 font: 1.5em Georgia, serif;
 color: #666;
}

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.