Created
February 6, 2011 16:28
-
-
Save fullstackplus/813487 to your computer and use it in GitHub Desktop.
Styled dropcaps with CSS and JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A function to turn the first letter of the main article of your blog into a styled dropcap. | |
See example here: http://jamesabbottdd.com/articles | |
Change the id of the first article to reflect your markup: | |
var main_entry = document.getElementById("main-entry"); | |
...and you're good to go. | |
*/ | |
function addDropCap() { | |
//separate the drop cap | |
var main_entry = document.getElementById("main-entry"); | |
var paragraphs = main_entry.getElementsByTagName("p"); | |
var first_paragraph = main_entry.getElementsByTagName("p")[0]; | |
var text = first_paragraph.innerHTML; | |
//some IE8 love | |
if (typeof String.trim == "undefined") { | |
String.prototype.trim = function() { | |
return this.replace(/(^\s*)|(\s*$)/g, ""); | |
} | |
} | |
text = text.trim(); | |
var first_letter = text.substr(0,1) | |
text = text.slice(1); | |
//create new DOM element | |
var dropcap = document.createElement("span"); | |
dropcap.className = "dropcap"; | |
dropcap.innerHTML = first_letter | |
var dcpar = document.createElement("p"); | |
dcpar.appendChild(dropcap); | |
var t = document.createTextNode(text); | |
dcpar.appendChild(t); | |
//remove old, append new | |
main_entry.removeChild(first_paragraph); | |
var second_paragraph = paragraphs[0]; | |
main_entry.insertBefore(dcpar, second_paragraph); | |
} | |
function addLoadEvent(func) { | |
var oldonload = window.onload; | |
if (typeof window.onload != 'function') { | |
window.onload = func; | |
} else { | |
window.onload = function() { | |
oldonload(); | |
func(); | |
} | |
} | |
} | |
addLoadEvent(addDropCap); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment