Skip to content

Instantly share code, notes, and snippets.

@jbuncle
Last active May 22, 2016 15:41
Show Gist options
  • Save jbuncle/397c80b35b55c5038e2a to your computer and use it in GitHub Desktop.
Save jbuncle/397c80b35b55c5038e2a to your computer and use it in GitHub Desktop.
jQuery Plugin to apply a 'smallcaps' effect to text
/*!
* jQuery SmallCaps
*
* Demo: https://jsfiddle.net/jbuncle/9wwrkbrf/
*
* Copyright 2013 James Buncle
*
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function($) {
$.fn.smallCaps = function() {
$.each($(this).contents(), function(index, obj) {
processNode(obj);
});
return this;
};
function processNode(element) {
if (element.nodeType === 3) {
var text = element.textContent;
if (text !== undefined) {
if (text.trim().length > 0) {
var newText = convertText(text);
$(element).replaceWith(newText);
$(element).css({
border: '0 none'
});
}
}
}
}
function convertText(text) {
var fontSize = "0.7em";
var newText = "";
var currUppers = "";
var currLowers = "";
var charIndex;
for (charIndex = 0; charIndex < text.length; charIndex++) {
var currChar = text.charAt(charIndex);
if (isUpper(currChar)) {
if (currLowers !== "") {
newText += wrapLower(currLowers, fontSize);
currLowers = "";
}
currUppers += currChar;
} else {
if (currUppers !== "") {
newText += wrapUpper(currUppers, fontSize);
currUppers = "";
}
currLowers += currChar;
}
}
if (currLowers !== '') {
newText += wrapLower(currLowers);
}
//Wrap up remainder
if (currUppers !== '') {
newText += wrapUpper(currUppers);
}
return newText;
}
function isUpper(character) {
return character.toUpperCase() === character;
}
function wrapUpper(text) {
return "<div style='display:inline;font-size:1em;'>" + text + "</div>";
}
function wrapLower(text, size) {
return "<div style='display:inline;font-size:0.7em;text-transform: uppercase'>" + text + "</div>";
}
function hasChildren($obj) {
return $obj.length > 0;
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment