Skip to content

Instantly share code, notes, and snippets.

@bruno-barros
Last active February 12, 2016 17:39
Show Gist options
  • Save bruno-barros/16416042324d505195b9 to your computer and use it in GitHub Desktop.
Save bruno-barros/16416042324d505195b9 to your computer and use it in GitHub Desktop.
<style>
.wrapliner {
background: yellow;
display: block;
margin-bottom: 5px;
}
</style>
(function ($) {
'use strict';
$.fn.wrapLines = function (options) {
var options = $.extend({
lineWrap: 'span',
lineClassPrefix: 'wrapliner wrap_line_',
wordClassPrefix: 'w_line_',
index: 0,
offsetTop: 0,
offsetLeft: 0
}, options);
return this.each(function () {
options.index = 0;
options.offset = 0;
var parentElm = $(this);
var elmText = $(parentElm).text();
$(parentElm).html(function (ind, htm) {
var $repText = '<' + options.lineWrap + '>' + elmText.replace(/\s+/g, ' </' + options.lineWrap + '> <' + options.lineWrap + '>');
$repText = $repText + '</' + options.lineWrap + '>';
return $repText;
});
$(options.lineWrap, parentElm).each(function () {
var spanOffset = $(this).offset();
if (spanOffset.top > options.offsetTop) {
options.offsetTop = spanOffset.top;
options.index++;
}
$(this).addClass(options.wordClassPrefix + options.index);
});
if ($.browser.msie && ($.browser.version == 7 || $.browser.version == 8)) {
for (var x = 1; x <= options.index; x++) {
var $spans = $('.' + options.wordClassPrefix + x);
$spans
.eq($spans.length - 1)
.removeClass(options.wordClassPrefix + x)
.addClass(options.wordClassPrefix + (x + 1))
}
}
for (var x = 1; x <= options.index; x++) {
$('.' + options.wordClassPrefix + x, parentElm)
.wrapAll('<' + options.lineWrap + ' class="' + options.lineClassPrefix + x + '" />')
.append("");
var innerText = $('.' + options.lineClassPrefix + x, parentElm).text();
$('.' + options.lineClassPrefix + x, parentElm).html(function () {
return innerText;
});
}
});
};
}(jQuery));
$(function(){
$('p').wrapLines();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment