Tuesday, 30 September 2014

How to detect width of text inside text box

In this tutorial we are going to see how to calculate the width of text inside the text box. First of all we need to know why we are trying to achieve this. This is useful when you want to position some text suggestion just beneath the user cursor inside the text box. The image given below will provide better understanding of the scenario.

In the above image you can see that suggestions are placed exactly beneath the present cursor. These type of hint suggestions are more intuitive to users. So how to achieve this ?. The answer is simple, get the width of the text inside the box and position the suggestion box accordingly. But currently there is no api who directly calculates the width of text. So what's the trick ?. The trick is simple
  • Create an HTML element on the fly ( with the help of javascript).
  • Populate that element with the content of input box.
  • Calculate width of created element (The returned width will be the width of the text inside created element).
For ex: 

<input type="text" onkeyup="evaluates(this)" />


function evaluates(dis)

function getWidth(dis)
    var prev = document.getElementById("created_one");

    var value = dis.value;
    var box = document.createElement("span");
    box.style.border = "0px";
    box.style.padding = "0px"; 
    box.style.visibility = "hidden";
    box.style.position = "absolute";
    box.style.zIndex = "-1";
    box.style.bottom = "0px";
    box.innerHTML = value;
    return parseInt( box.offsetWidth );

Remember that the font size for both the elements i.e the text box and the created element should be the same. The width calculated will not count the margin and padding of the text box.

No comments:

Post a comment