1

I need a way to predict the width of a string if it were to be added inside an element.

The font size is 16px. My original idea was to do 16px for every character but that ended up being wrong.. Any ideas?

THE AMAZING
  • 1,496
  • 2
  • 16
  • 38
  • Still confusing, add more information to your question. – Praveen Aug 26 '13 at 05:22
  • [This](http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/) might help. (Inspired by a [previous question](http://stackoverflow.com/questions/1472303/jquery-get-width-of-element-when-not-visible-display-none).) – Taymon Aug 26 '13 at 05:24
  • its given you add hidden element append all text to it and get its width – Muhammad Umer Aug 26 '13 at 05:49

1 Answers1

1

You can append the string to the body like so:

function get_width_of_string() { 
    var div = document.createElement('div');
        div.style.position = "absolute";
        div.style.marginLeft = "-99999px";
        div.style.display = "inline-block";
    div.innerHTML =  "this is a  string";

    document.body.appendChild(div);

    var width = div.offsetWidth;
    document.body.removeChild(div);
    return width;
}

this should return the width of the string

Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28