left-side version of overflow: ellipses

by Graham Dixon

HTML

<div id="container" >
    <div id="test">This text is far too long for this div</div>
    <div>Test text line two. Text is a bit longer on this line so that the overflows happen at different places!</div>
</div>
<!--TEST THIS BY RESIZING THE 'RESULT' BOX, NOT THE WINDOW-->

CSS

#container {
    width: 100%;
    border: 1px solid blue;
}

#container div {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
}

JavaScript

/**
 * Simple jquery function to trim a line of text with ellipses on left side,
 * like text-overflow: ellipsis clip will in Firefox only.  Changes the text 
 * permanently, so the amount of text hidden will not change when the window
 * is resized.
 * For this to work, the element you pass in needs to have overflow: hidden
 * and white-space: nowrap;
 * 
 * http://stackoverflow.com/questions/9793473/text-overflow-ellipsis-on-left-side
 * updated to support resize like http://jsfiddle.net/sP9AE/1/ 
 * Adapted by Graham Dixon. [email protected]
 */


(function($) {

    $.trimLeft = function(element, options) {

		var trim = this;

        var $element = $(element), // reference to the jQuery version of DOM element
             element = element;    // reference to the actual DOM element

        var initialText = element.innerHTML;
        
        trim.init = function() {
            overrideNodeMethod("html", function(){ return initialText; });
            trimContents(element, element);
            return trim;
        };
        
        trim.reset = function(){
            element.innerHTML = initialText;
            return trim;
        };
        
        //Overide .html() to return initialText.
        var overrideNodeMethod = function(methodName, action) {
            var originalVal = $.fn[methodName];
            var thisNode = $element;
            $.fn[methodName] = function() {
                if (this[0]==thisNode[0]) {
                    return action.apply(this, arguments);
                } else {
                    return originalVal.apply(this, arguments);
                }
            };
	    };

		var trimContents = function(row, node){
	        while (row.scrollWidth > row.offsetWidth) {
	            var childNode = node.firstChild;
	            if (!childNode)
	                return true;            
	            if (childNode.nodeType == document.TEXT_NODE){
	                trimText(row, node, childNode);
	            }
	         ...