Created
January 22, 2014 22:59
-
-
Save tkambler/8569187 to your computer and use it in GitHub Desktop.
Given an element with a CSS value for 'max-height', this plugin will allow you to wrap any text that overflows the bounds of the element with a specified class name.
This file contains hidden or 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
/** | |
* Given an element with a CSS value for 'max-height', this plugin will allow you | |
* to wrap any text that overflows the bounds of the element with a specified class | |
* name. | |
* | |
* Example: | |
* | |
* $(".container").trevanify('wrapping_class'); | |
*/ | |
$.fn.trevanify = function(overflow_class) { | |
var width = $(this).width(), | |
height = $(this).height(), | |
$tmpContainer = $("<div></div>"), | |
maxHeight = parseInt($(this).css('max-height'), 10) || null, | |
overflow = '', | |
start; | |
if ( maxHeight === null ) { | |
throw 'Target must have a value specified for max-height.'; | |
} | |
$tmpContainer.css({ | |
'width': width, | |
'max-width': width, | |
'position': 'absolute', | |
'left': -20000, | |
'top': -20000 | |
}); | |
$('body').append($tmpContainer); | |
var text = $.trim($(this).text()); | |
$(this).text(text); | |
var content = $(this).contents().first(); | |
var txt_array = text.split(''), | |
previousContent, | |
previousText; | |
for ( var i = 0; i < txt_array.length; i++ ) { | |
if ( overflow || $tmpContainer.height() > maxHeight ) { | |
$tmpContainer.html(previousContent); | |
if ( previousText ) { | |
overflow += previousText + txt_array[i]; | |
previousText = null; | |
} else { | |
overflow += txt_array[i]; | |
} | |
} else { | |
previousContent = $tmpContainer.html(); | |
previousText = txt_array[i]; | |
$tmpContainer.html(previousContent + txt_array[i]); | |
start = i; | |
} | |
} | |
var tmp = text.split(''), | |
overflow_class = overflow_class || 'overflow'; | |
replacement = "<span class='" + overflow_class + "'>" + overflow + "</span>"; | |
tmp.splice(start, tmp.length - start, replacement); | |
tmp = tmp.join(''); | |
$(this).html(tmp); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment