tags:

views:

140

answers:

3

I need to set a maximum widht to a label tag and avoid the text overflow with jquery.

Is there an elegant way to do it?

A: 

You can do this:

$("label").wrap("<div style='width: 200px;'></div>");

Or, better overall, use CSS like this:

.labelWrap { width: 200px; }

And jQuery like this to use it:

$("label").wrap($("<div />", {"class":"labelWrap"}));
Nick Craver
+1  A: 

You could use a class:

... in the css

.elegance{
  overflow:hidden;
  max-width:400px; /* or just width, depending on what you want*/
  display:inline-block;
}

... on document ready

$("label").addClass("elegance");

Or just wrap a div around it using

$("label").wrap("<div class='elegance'></div>");

If you don't want to use separate css, you can set it on the fly using .css()

marcgg
+1  A: 

Specify a width, width: 50px (say), on the label. Since label is an inline element, you also need to specify display: block.

Now, what do you want to do in the case of an overflow? If you simply want to hide the text that doesn't fit, use overflow: hidden. If you want it to wrap to the next line, it'll automatically do this as per the specifications above, unless there is a long piece of non-breakable text (i.e. that doesn't contain any whitespace). In that case, you need to identify the string of characters that would be too long (I've used 15 in the example below), and inject a space between them:

$('#wrap').text($('#wrap').text().replace(/(\S{15})/g, '$1 '));
David Hedlund
Ok this solution is really cool.The problem is with different fonts not monospace.With these fonts strings with the same caracters length have different width.So the problem now is when to insert the blank character....Any idea?
Massimo Ugues