Created
November 4, 2009 20:56
-
-
Save mikehale/226365 to your computer and use it in GitHub Desktop.
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
| (function($) { | |
| $.fn.ellipsis = function(enableUpdating) { | |
| function supportsOverflowProperty() { | |
| var s = document.documentElement.style; | |
| return ('textOverflow' in s || 'OTextOverflow' in s); | |
| } | |
| function updateText(originalString, scratchElement, length) { | |
| var text = originalString.substr(0, length); | |
| scratchElement.html(text + "…"); | |
| return text; | |
| } | |
| this.each(function() { | |
| $(this).css({ 'overflow': 'hidden', 'white-space': 'nowrap' }); | |
| }); | |
| return this.each(function() { | |
| var actualElement = $(this); | |
| var originalText = actualElement.html(); | |
| var actualElementWidth = actualElement.width(); | |
| if (!supportsOverflowProperty()) { | |
| var text = originalText; | |
| var scratchElement = $(this.cloneNode(true)).hide().css({ | |
| 'position': 'absolute', | |
| 'width': 'auto', | |
| 'overflow': 'visible', | |
| 'max-width': 'inherit' | |
| }); | |
| actualElement.after(scratchElement); | |
| if (text.length > 0 && scratchElement.width() > actualElementWidth) { | |
| actualElement.attr("title", originalText); | |
| var textLengthApproximation = Math.floor(text.length * actualElementWidth / scratchElement.width()); | |
| text = updateText(originalText, scratchElement, textLengthApproximation); | |
| while (text.length < originalText.length && scratchElement.width() < actualElementWidth) { | |
| text = updateText(originalText, scratchElement, text.length + 1); | |
| } | |
| while (text.length > 0 && scratchElement.width() > actualElementWidth) { | |
| text = updateText(originalText, scratchElement, text.length - 1); | |
| } | |
| } | |
| actualElement.html(scratchElement.html()); | |
| scratchElement.remove(); | |
| if (enableUpdating == true) { | |
| var oldW = actualElement.width(); | |
| setInterval(function() { | |
| if (actualElement.width() != oldW) { | |
| oldW = actualElement.width(); | |
| actualElement.html(originalText); | |
| actualElement.ellipsis(); | |
| } | |
| }, 200); | |
| } | |
| } else { | |
| actualElement.css({ | |
| 'text-overflow': 'ellipsis', | |
| '-o-text-overflow': 'ellipsis' | |
| }); | |
| actualElement.attr("title", originalText); | |
| } | |
| }); | |
| }; | |
| })(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment