In Fancy Drop Cap - Part 1, I showed how I used jQuery to insert a drop cap on my personal weblog. But there is still some unfinished business to take care of:
- Accounting for cases in which the first paragraph (where I want my drop cap to go) starts with another tag of some sort (
<a href="...">, <em>, etc.)
- Adding a little CSS to the drop cap
So let's begin with item 1. As you may recall, we defined three variables, first_paragraph, first_letter, and text. The variables allowed us to get the value of the textNode of the first letter of the first paragraph, so we could replace it with the image. Here is what that part looked like:
JavaScript:
-
var first_paragraph = $('#main-content p')[0];
-
if (!first_paragraph) return false;
-
var text = first_paragraph.
firstChild.
nodeValue;
-
var first_letter =
text.
substr(0,
1);
-
-
first_paragraph.
firstChild.
nodeValue =
text.
slice(1);
-
}
The only problem with that code is that line 3 assumes that the first child node of the first paragraph is actually a text node. But what if it's a span tag (<span>) or a link (<a href="...">)? Well, in that case we'll need to keep drilling down through the nodes until we can't go any farther.
Loop the Loop
To do that, we'll set an intermediate variable, called node, initially making it the same as first_paragraph:
JavaScript:
-
var node = first_paragraph;
Next, we change our node variable to be defined as the first child of that node (node = node.firstChild), and we keep doing that until there are no more child nodes left, by using a "while" loop:
JavaScript:
-
while (node.
childNodes.
length) {
-
node = node.firstChild;
-
}
So, in other words, as long as there is a child node, our variable will be reset as that child node.
The First Letter — and Only a Letter
When that's all done, we set our text variable, this time as the value of our node variable:
JavaScript:
-
var text = node.
nodeValue;
Now all we have to do is get the first letter of the text so that we can replace it with the drop-cap image: var first_letter = text.substr(0,1).
There is just one more thing that we should account for (more...)