Sir2B
Sir2B

Reputation: 1079

Get width of text in span with text-overflow: ellipsis; at IE11

I have a span which is in a div with text-overflow set:

<div id="parent" style="width: 50px; overflow: hidden; text-overflow: ellipsis;">
  <span id="child">exampleasdaadasdsfdgs</span>
</div>

When I try to get the width of the text in the span, I tried:

$("#child").width();

In most browsers it works, but in IE 11 (perhaps in more) it doesn't. When I delete "text-overflow: ellipsis;" it shows the correct length of the text.

I made a fiddle for testing.

Is there a good (and not to slow) method for getting the width with IE11, except from getting the length of the text and multiply it with the font-size?

Upvotes: 2

Views: 2601

Answers (3)

Sir2B
Sir2B

Reputation: 1079

My solution I use now, is to remove the style {text-overflow: ellipsis;} and add it after the measurement again.

$("#parent").css("text-overflow", "clip");
$('#childwidth').html($("#child").width());
$("#parent").css("text-overflow", "ellipsis");

For me this is at the moment the best solution (see jsfiddle). I have a relativ complex layout, which much relativ lengths and it would take more time to reproduce this layout.

Upvotes: 0

Yanaro
Yanaro

Reputation: 345

This is another answer that i came up with, though it might not work at times, span get display block style and padding from parent for example. Position can also be absolute. This works by creating new element, append it to a parent or body, measure its width then delete it.

function textWidth(text, parent) {
     var textElement = $('<span style="opacity:0; position: fixed; overflow: visible" class="it_has_similar_style_as_the_one_we_need_to_measure">' + text + '</span>');
     //if you have a parent element, append it here so it can inherit some necessary styles
     if(!parent) {
        $(document.body).append(textElement);
     } else {
        parent.append(textElement);
     }
     var width = textElement.width();
     textElement.remove();
     return width;
}

Upvotes: 0

Yanaro
Yanaro

Reputation: 345

If you know font size and font family, you can use canvas measureText() to get text width

function textWidth(text, font) {
 font = font || "16px Arial"
 var c = document.createElement('canvas');
 var ctx = c.getContext("2d");
 ctx.font = font;
 return ctx.measureText(text).width;
}

var myText = $('#mySpan').html();
console.log(textWidth(myText))

Remember that it only works if you know the font size and font family before hand.

Upvotes: 2

Related Questions