Created
June 21, 2012 11:27
-
-
Save Sleavely/2965222 to your computer and use it in GitHub Desktop.
Building Klarna-style underlines
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
/** | |
Requires jQuery. | |
Built, with love, by Joakim Hedlund <joakim.hedlund@klarna.com> | |
*/ | |
jQuery.fn.lastLineWidth = function(text){ | |
var $this = jQuery(this), | |
$tmpHtml = jQuery('<span style="postion:absolute;width:auto;left:-9999px"></span>'); | |
var containerWidth = $this.width(), //width of the container (e.g. <h1>) | |
lineNumber = 0, //current line that we are parsing | |
lineText = '', //text so far on this line | |
lineWidth = 0, //current line's width | |
wordWidth = 0; //current word's width | |
//split the string into words to make it easier to keep track of when a line break occurs | |
var textString = (text || $this.text()); | |
var textArr = textString.split(" "); | |
//only look up original font properties once, thus outside of for() loop | |
$tmpHtml.css("font-family", $this.css("font-family")); | |
$tmpHtml.css("font-size", $this.css("font-size")); | |
$tmpHtml.css("font-weight", $this.css("font-weight")); | |
//add our playground to the rendered area | |
jQuery("body").append($tmpHtml); | |
//go through each word and line | |
for(var i = 0; i < textArr.length; i++){ | |
$tmpHtml.text(textArr[i]); | |
wordWidth = $tmpHtml.width(); | |
if((lineWidth + wordWidth + $tmpHtml.html(" ").width()) >= containerWidth){ | |
//word will be placed on new line | |
lineNumber++; | |
lineText = ''; | |
lineWidth = 0; | |
} | |
//if theres previous text, append it | |
if(lineText.length > 0){ | |
lineText = lineText + " " + textArr[i]; | |
$tmpHtml.text(lineText); | |
}else{ | |
lineText = textArr[i]; | |
} | |
lineWidth = $tmpHtml.width(); | |
} | |
$tmpHtml.remove(); | |
return lineWidth; | |
} | |
jQuery(document).ready(function(){ | |
jQuery("h1").not(".notag").each(function(){ | |
var $this = jQuery(this); | |
var tagWidth = $this.lastLineWidth(); | |
var xOffset = -318 + tagWidth * 0.25; | |
var $tag = jQuery('<span> </span>'); | |
$this.addClass("tag") | |
$this.css('position', 'relative'); | |
$tag.css({ | |
'background-position': xOffset + 'px 0px', | |
'background-image': 'url(https://static.klarna.com/internal/img/templates/h1_tag.png)', | |
'background-repeat': 'repeat-x', | |
'bottom': '0px', | |
'display': 'inline-block', | |
'height': '30px', | |
'left': '0px', | |
'position': 'absolute', | |
'width': tagWidth + 'px' | |
}); | |
$this.append($tag); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment