10
X

Multiple Fancy Drop Caps

read 18 comments

After I wrote a couple entries (Fancy Drop Cap, Part 1 and Part 2) on creating a drop cap for the first paragraph in a DIV, a couple people asked how one would go about making the drop cap apply to every paragraph in a DIV.

Update

I've written a Fancy Letter Plugin that does all the hard work for you. You write a line of jQuery like $('div.content p').fancyletter(). The plugin wraps the first letter of the selected elements in a <span> with class names that you can then style to your needs.

Most of the code can remain the way we left it in Fancy Drop Cap - Part 2. We created a swap_letter() function to:

Continue Reading Below
  1. find the first letter of the paragraph
  2. concatenate that letter with the rest of an image tag if it matches one of the letters in a regular expression
  3. strip the letter out of the paragraph since we want to replace it with the image
  4. prepend the image tag to the paragraph

We also gave the image a class name of "fancy-letter" so that we could style it a bit:

CSS:
  1. .fancy-letter {
  2.  float: left;
  3.  margin: -1px 2px 2px 0;
  4. }

So, what needs to change? Not much actually.

The first thing to do is remove the line that sets the "first_paragraph" variable: var first_paragraph = $('#main-content p')[0]. In its place we'll use jQuery's .each(), which takes the pain out of for loops. All of the work will be done inside this .each() method, starting with setting a variable for "each" of the paragraphs:

JavaScript:
  1. $('#drop-caps p').each(function(index) {
  2.   var paragraph = this;
  3.   . . .
  4. });

We set the paragraph variable as this instead of $(this) for the same reason that we had (in the earlier entries) put the [0] after $('#main-content p') instead of writing $('#main-content p:eq(0)'): because we need to work on the actual DOM node. Also, note that I changed the DIV's id from "main-content" to "drop-caps" for this example, but you can name yours whatever you want.

The rest of the code is pretty much the same, because all we really needed to do was get a different set of elements Here is the new code in all its glory:

JavaScript:
  1. $(document).ready(function(){
  2.   swap_letter();    
  3. });
  4. function swap_letter() {
  5.   $('#drop-caps p').each(function(index) {
  6.     var paragraph = this;
  7.     var node = paragraph;
  8.     while (node.childNodes.length) {
  9.       node = node.firstChild;
  10.     }
  11.     var text = node.nodeValue;
  12.     var first_letter = text.substr(0,1);
  13.  
  14.     var match = /[a-zA-Z]/.test(first_letter);
  15.     if ( match ) {
  16.       node.nodeValue = text.slice(1);
  17.       $('<img />')
  18.           .attr('src','/images/alphabet/' + first_letter.toLowerCase() + '.gif')
  19.           .attr('alt',first_letter)
  20.           .addClass('fancy-letter')
  21.           .prependTo( paragraph );
  22.       first_letter = "";
  23.     }
  24.   });
  25. }

For an explanation of the other parts, please refer to Fancy Drop Cap - Part 2 and Fancy Drop Cap - Part 1. In the meantime, feast your eyes on the beauty of these fancy first letters.

This is the first paragraph. The "T" in "This" should be replaced by the drop-cap image. The image is floated left with a little padding to the right and the bottom.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.


comment feed

18 comments

  1. Ty

    Hey cool, I'm stuck with trying to design a site around an old-english lettering styled large logo.
    Why did drop caps never occur to me. This may be easier to setup for some than sIFR.
    I might just give it a try.
    thanks.

  2. Ty

    Another thought on creating the images required would be to put the whole font character set together in imageReady or Fireworks. Drag out guides to seperate all the letters, and then click create slices from guides. Now save the slices and you're ready to rock and roll!

  3. Yeah, slicing is a good idea for getting those letters ready. Thanks for the tip!

  4. Kingsley

    It'd be even better to make a sprite grid out of all the letters.

    • tk

      @kinglsey The code would need a bit of modification to apply separate styles to each letter instance in a sprite.... I have a need to load different color instances of the versal for a dynamically changing layout within a single site design. I may try and hash something like this out, which would make the code work with a sprite grid. I'll post a link to the code when its up, in case anyone wants to check it out and use it.

  5. Jurriaan

    I didn't want to use the image replacement but just a bigger font for the first letter. I could've used the first-letter tag in css but since this doesn't work in IE6 I used the code below to replace the first letter of all paragraphs.

    
    		  swap_letter();
    				});
    				function swap_letter() {
    				  $('#content p').each(function(index) {
    					var paragraph = this;
    					var node = paragraph;
    					while (node.childNodes.length) {
    					  node = node.firstChild;
    					}
    					var text = node.nodeValue;
    					var first_letter = text.substr(0,1);
    					var match = /[a-zA-Z]/.test(first_letter);
    					if ( match ) {
    					  node.nodeValue = text.slice(1);
    					  $('')
    						  .text( first_letter )
    						  .addClass('eerste-letter')
    						  .prependTo( paragraph );
    					  first_letter = "";
    					}
    				  });
    				}
    
    

    CSS

    
    #content .eerste-letter 
    font-size:2.5em;
    line-height:90%;
    padding-right:3px;
    text-transform:uppercase;
    }
    
    
  6. Jurriaan

    I'm sorry i pasted the wrong code

    
    swap_letter();
    	});
    	function swap_letter() {
    	  $('#content p').each(function(index) {
    		var paragraph = this;
    		var node = paragraph;
    		while (node.childNodes.length) {
    		  node = node.firstChild;
    		}
    		var text = node.nodeValue;
    		var first_letter = text.substr(0,1);
    		var match = /[a-zA-Z]/.test(first_letter);
    		if ( match ) {
    		  node.nodeValue = text.slice(1);
    		  $('')
    			  .text( first_letter )
    			  .addClass('eerste-letter')
    			  .prependTo( paragraph );
    		  first_letter = "";
    		}
    	  });
    	}
    
    
  7. Jurriaan

    sorry i pasted the wrong code

    
    swap_letter();
    	});
    	function swap_letter() {
    	  $('#content p').each(function(index) {
    		var paragraph = this;
    		var node = paragraph;
    		while (node.childNodes.length) {
    		  node = node.firstChild;
    		}
    		var text = node.nodeValue;
    		var first_letter = text.substr(0,1);
    		var match = /[a-zA-Z]/.test(first_letter);
    		if ( match ) {
    		  node.nodeValue = text.slice(1);
    		  $('')
    			  .text( first_letter )
    			  .addClass('eerste-letter')
    			  .prependTo( paragraph );
    		  first_letter = "";
    		}
    	  });
    	}
    
    
  8. Jurriaan

    wtf it deletes my span tag

  9. Jurriaan,

    Did you use &lt; instead of < and &gt; instead of >? (see "IMPORTANT" above comment textarea.)

  10. Thanx For sharing such a beautiful resource. I really appreciate it..

  11. Lee

    .prependTo( paragraph );

    This line, I think has a little problem.

    If the first letter is a child of an "a" ancor, after swapping, the first letter will no longer be a child of the "a" ancor.

  12. Would there be a way to add the dropcap to the first paragraph of a and every time I used that class for a div it would add a dropcap to the 1st paragraph.

    For example (on the same document):

    Blah, blah, blah ...

    later in that same document...
    Blah, blah, blah ...

    Each contain several paragraphs that are NOT dropcapped...??

    Make sense?

  13. Hi Kenet,
    It looks like part of your comment was lost. In any case, you can add a drop cap to anything you want by using my Fancy Letter Plugin. You just apply it as you would any other jQuery method, indicated the elements in a selector expression. For example, $('div.entry p:first').fancyletter();

  14. mario

    hello karl!
    firstly i want to thank you on a nice code you are giving here..
    though have one question or rather if i may say so- remark...
    What about Eastern European Characters? when my paragraph begins with one of these nothing is happenig ie there is no really drop caps? It is possible to get that too with this code? if it is can you please show an example how that par of a code should go?
    thank you
    mario :-)

  15. mario

    hi Karl again!
    i played for a while with this line of a code:
    var match = /[a-zA-Z]/.test(first_letter);
    so i put last cahacter of Croatian character at the end and it seems now that everything is working
    so i have now:
    var match = /[a-žA-Ž]/.test(first_letter);
    thanx though! :-)

    ill post link to the site when i will finish it bc im using some really light cool stuff from these page! :-)

    cheers

  16. Adam Silverman

    I am working through this as a tutorial running jQuery 1.4. I had trouble with the

    $('<img />').src()

    I am guessing that the ".src()" function maybe doesn't work anymore, or I typed something incorrectly :)

    I changed it to the following and it worked for me...

    $('<img />')
     .attr('src', 'alphabet/' + first_letter.toLowerCase() + '.gif')
     .attr('alt',first_letter)
     .addClass('fancy-letter')
     .prependTo( first_paragraph );
    

    Does that make sense?

26 Pings

  1. MiracleStudios.us Blog » Blog Archive » 37 More Shocking jQuery Plugins

    [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  2. [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  3. [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  4. [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  5. 65 Excellent jQuery Resources (tutorials,cheat sheets,ebooks,demos,plugins…) : Speckyboy - Web Design, Web Development and Graphic Design Resources

    [...] Ajax development with jQuery 11. Rounded Corners 12. Getting Around The Minimum Height Glitch 13. Multiple Fancy Drop Caps 14. Semitransparent rollovers made easy with JQuery 15. Using JQuery to modify presentation while [...]

  6. [...] 30) crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a DIV. [...]

  7. [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  8. 37 More Shocking jQuery Plugins at Expertz

    [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  9. 我就是老刘~ » 37个更加出色的jQuery插件

    [...] crop, labelOver and pluck- [...]

  10. [...] 3. Multiple Fancy Drop Caps – Learning jQuery Applying drop caps to every paragraph in a div. [...]

  11. Best jquery plugins examples,Jquery-css gallery, css scripts showcase ,php scripts,ajax scripts,CMS Drupal,CMS Joomla,CMS WordPress:W3CGallery.com

    [...]   crop, labelOver and pluck and apply it to every paragraph in a DIV. [...]

  12. [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  13. 40多个jquery插件 | QK31

    [...] Tutorial Link [...]

  14. PHP-help » Excellent jQuery Tutorials

    [...] Tutorial Link Related Posts:10 Steps to Becoming a Great Web DeveloperUltimate Collection of PHP Libraries10 Practical PHP Regular Expression RecipesPHP Tutorials for PHP Programmer20 Great PHP Libraries You Need to KnowShare/Bookmark [...]

  15. [...] crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a [...]

  16. [...] drop caps: those giant, sometimes fancy letters that come at the beginning of paragraphs (think medieval literature and art history textbooks). still in use today, even on the web, drop caps are easily programmable using CSS or jquery. [...]

  17. [...] development with jQuery 11. Rounded Corners 12. Getting Around The Minimum Height Glitch 13. Multiple Fancy Drop Caps 14. Semitransparent rollovers made easy with JQuery 15. Using JQuery to modify presentation while [...]

  18. [...] 30) crop, labelOver and pluck- How to create a drop cap and apply it to every paragraph in a DIV. [...]

  19. [...] Fancy Letter Plugin | Part 2 Multiple Fancy Drop [...]

Sorry, but comments for this entry are now closed.