views:

40

answers:

2

How do you prevent formatted user input past a max width? (e.g., 800 pixels) The user input is formatted because it is entered into a WYSIWYG text editor (CK Editor).

This solution doesn't work:

// Replicate user input in hidden div  
// Check width  
// If width > 800px, remove characters

...because you'd be removing characters from a formatted entry - e.g., from <p>Hello World</p> you'd end up with <p>Hello World</p

A: 

Can we assume only a certain font will be used? This one might help:

http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript

Jerome
Unfortunately not. But I can already find the width of the formatted string. The problem is in the actually shortening of it.
Emile
+1  A: 

I can already find the width of the formatted string. The problem is in the actually shortening of it.

I think given your problem it is possible to remove the last char from a formatted entry. You'd just have to recursively dig through your HTML structure till you find it. Have a look at this neat little function I've written:

function findLastElement(element){
    var content = $.trim(element.html());

    if(content.charAt(content.length - 1) === '>'){
        var lastChild = element.children(':last');
        if(lastChild.length > 0){
          return findLastElement(lastChild);
        }
    }

    return element;
}

The name is slightly misleading, but this function will dig through the jQuery element you pass to it to find the element containing the last character, so I think this will solve your problem.

PS. I'd readily accept any suggestion on how to optimize/adopt best practice with this piece of code, if any of the gurus here would kindly drop one in the comments.

Yi Jiang
Thank you for this!
Emile