This blog and domain is up for sale, contact us at street_demons@rocketmail.com

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)" />

JavaScript

function evaluates(dis)
{ 
    alert(getWidth(dis));
}

function getWidth(dis)
{
    var prev = document.getElementById("created_one");
    if(prev)
        document.body.removeChild(prev)

    var value = dis.value;
    var box = document.createElement("span");
    box.setAttribute("id","created_one");
    box.style.width="auto";
    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;
    document.body.appendChild(box);
    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