Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dimensions of text block via JavaScript, not the size of container's `getBoundingClientRect`

I want to get the size of text inside a container. Let's consider general case when the container has padding and border.

The problem is that getBoundingClientRect returns the size of text PLUS left border and padding, in case the text overflows. Otherwise it returns just the size of border box of the container.

enter image description here

like image 555
Dan Avatar asked Dec 16 '14 19:12

Dan


2 Answers

You can get the width if you create a placeholder div with all of the same text formatting options and find it's width.

For instance, I will create a div with the class .hidden that has the same attributes as the original div.

div.container
{
    font-size: 16px;
}

div.hidden
{
    font-size: 16px;
    display: none;
}

Then, using jQuery, copy the contents of .container to .hidden and find the width of .hidden:

$(function(){

    $("div.container").each(function(){
   
        $("body").append("<div class='hidden'>"+$(this).html()+"</div>");
        var width = $("div.hidden").width();
        $("div.width").html("Actual width: "+width+"px");
        $("div.hidden").remove();
    
    });

});

JSFiddle

like image 106
Liftoff Avatar answered Oct 23 '22 09:10

Liftoff


Interesting! You could use javascript to clone the text inside of an empty element offscreen that has 0 padding/margin/border. Then you could get the width of that element.

var txt = document.getElementById('fixed').innerHTML,
    clone = document.getElementById('clone');

clone.innerHTML = txt;

var width = clone.offsetWidth;

document.getElementById('output').innerHTML = width;
#fixed {
    width: 8em;
    height: 8em;
    border: .5em solid red;
}

#clone { 
  margin: 0;
  padding: 0;
  border: 0;
  position: fixed;
  left: -9999px;
}
<div id="fixed">asdfkjahsdflkahjsdflkjhasdljfhalsdkjfhalsdkjfhalsdkjfhalksdhjflasd</div>
<div id="clone"></div>

Width of text: <span id="output"></span>
like image 2
Barry T. Smith Avatar answered Oct 23 '22 08:10

Barry T. Smith