Angular directive that dynamically change input box width respective to the placeholder
Recently I get with a requirement to dynamically change input box width respective to the placeholder length. Now I am going to give a small heads up about use case and how I accomplished the task.
This application is developed with angularJs. As it has multiple language support placeholder also changes respective to the language. For some of the language, placeholder is not fully visible and for some of the language, the input box width was too large compared to the placeholder. So here the mission is to dynamically change the width of the input box respective to the placeholder length.
To accomplish the above mission I create a custom directive to change the width of the input box dynamically. Here the challenge is to find the width of the placeholder. The length property of the placeholder will give you the character count. Using that we can’t able to find the element width of the placeholder text.
In this directive, I used two key things to find the width of the placeholder text
- Font size – this will get the current font size used in the input box
- <span> – Sudo element to calculate the actual element width of the placeholder
Calculating the Font Size
The below given js code will return the font size used in the input box which invoked this directive
var fontSize = parseFloat(window.getComputedStyle(elem, null).getPropertyValue('font-size'));
After that dynamically create a pseudo element with the style of above identified font size because this will help us to get the exact width of the placeholder content. Once the process of identifying the width is donr then the pseudo element got removed from the DOM.
minwidth – in addition, this attribute will set the minimum width for the input box
bufferwidth – in addition, this attribute will add buffer with for input box for better readability and appearance.
Angular Directive to Dynamically Adjust input box width respective to the placeholder length
See the Pen Angular Directive to Dynamically Adjust input box width respective to the placeholder length by icodefy (@icodefy) on CodePen.0
You can find the working snippest here. Drop your suggestion and valuble comments.