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

Kyle Cureau
  • 19,028
  • 23
  • 75
  • 104
  • Keep in mind, that the browser of the editor may have different settings/fonts/etc. than the browser of the viewer later, so that the text will be wider than 800px in the viewers browser. – RoToRa Aug 31 '10 at 10:51

2 Answers2

1

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
  • 49,435
  • 16
  • 136
  • 136
0

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

Calculate text width with JavaScript

Community
  • 1
  • 1
Jerome
  • 1,162
  • 1
  • 6
  • 12
  • Unfortunately not. But I can already find the width of the formatted string. The problem is in the actually shortening of it. – Kyle Cureau Aug 31 '10 at 10:28