- Get input text width when typing
- 5 Answers 5
- I see two ways.
- Font and Text Functions (Windows GDI)
- Obsolete Functions
- Calculating Text Width with PHP GD
- 2 Answers 2
- How to get Text Width
- How to get Text Width
- How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- RE: How to get Text Width
- Red Flag Submitted
- Reply To This Thread
- Posting in the Tek-Tips forums is a member-only feature.
Get input text width when typing
I have a input type text
When i start typing text inside input, i should be able to get the lenght of the entered text.
This is what I tried:
These two does not give the width of the text entered
Basically what I want is:
For suppose input text width is 320px . I need the width of the entered text i.e 120px , which keeps on changing when I enter.
5 Answers 5
I see two ways.
First:
You can use a div with content editable instead input. Like this you can see the width of the div.
Note : Like @Leon Adler say, this way allows pasting images, tables and formatting from other programs. So you maybe need some validation with javascript to check the content before get the size.
Second:
Use an input type text and past the content into an invisible div. And you can see the width of the invisible div.
Note : For this way, you must have the same font and font size on input and div tags.
I have modified Chillers answer slightly, because it looks like you wanted the width rather than the letter count. I have created a span, which is absolute positioned off the screen. I am then adding the value of the input to it and then getting the width of the span. To make it more fancy you could create the span with javascript.
Note that the input and the span would have to have the same CSS styling for this to be accurate.
UPDATE
Two things I want to put forward
Doing display none will not give you any offsetWidth if we are trying using vanilla JS. we can use visibility: hidden; or opacity:0 for that.
we need to add overflow:auto to the hidden span or else the text will be warped to the next line if it exceeds the browser window width and the width will stay fixed (width of window)
OLD
You can try this approach
Add a span and hide it
and then onkeyup add the text of the textfield on your hidden span and get its width.
WITH THE HELP OF JQUERY
SNIPPET (UPDATED)
USING JS ONLY
SNIPPET (UPDATED)
Font and Text Functions (Windows GDI)
The following functions are used with fonts and text.
Function | Description |
---|---|
AddFontMemResourceEx | Adds an embedded font to the system font table. |
AddFontResource | Adds a font resource to the system font table. |
AddFontResourceEx | Adds a private or non-enumerable font to the system font table. |
CreateFont | Creates a logical font. |
CreateFontIndirect | Creates a logical font from a structure. |
CreateFontIndirectEx | Creates a logical font from a structure. |
DrawText | Draws formatted text in a rectangle. |
DrawTextEx | Draws formatted text in rectangle. |
EnumFontFamExProc | An application definedcallback function used with EnumFontFamiliesEx to process fonts. |
EnumFontFamiliesEx | Enumerates all fonts in the system with certain characteristics. |
ExtTextOut | Draws a character string. |
GetAspectRatioFilterEx | Gets the setting for the aspect-ratio filter. |
GetCharABCWidths | Gets the widths of consecutive characters from the TrueType font. |
GetCharABCWidthsFloat | Gets the widths of consecutive characters from the current font. |
GetCharABCWidthsI | Gets the widths of consecutive glyph indices or from an array of glyph indices from the TrueType font. |
GetCharacterPlacement | Gets information about a character string. |
GetCharWidth32 | Gets the widths of consecutive characters from the current font. |
GetCharWidthFloat | Gets the fractional widths of consecutive characters from the current font. |
GetCharWidthI | Gets the widths of consecutive glyph indices or an array of glyph indices from the current font. |
GetFontData | Gets metric data for a TrueType font. |
GetFontLanguageInfo | Returns information about the selected font for a display context. |
GetFontUnicodeRanges | Tells which Unicode characters are supported by a font. |
GetGlyphIndices | Translates a string into an array of glyph indices. |
GetGlyphOutline | Gets the outline or bitmap for a character in the TrueType font. |
GetKerningPairs | Gets the character-kerning pairs for a font. |
GetOutlineTextMetrics | Gets text metrics for TrueType fonts. |
GetRasterizerCaps | Tells whether TrueType fonts are installed. |
GetTabbedTextExtent | Computes the width and height of a character string, including tabs. |
GetTextAlign | Gets the text-alignment setting for a device context. |
GetTextCharacterExtra | Gets the current intercharacter spacing for a device context. |
GetTextColor | Gets the text color for a device context. |
GetTextExtentExPoint | Gets the number of characters in a string that will fit within a space. |
GetTextExtentExPointI | Gets the number of glyph indices that will fit within a space. |
GetTextExtentPoint32 | Computes the width and height of a string of text. |
GetTextExtentPointI | Computes the width and height of an array of glyph indices. |
GetTextFace | Gets the name of the font that is selected into a device context. |
GetTextMetrics | Fills a buffer with the metrics for a font. |
PolyTextOut | Draws several strings using the font and text colors in a device context. |
RemoveFontMemResourceEx | Removes a font whose source was embedded in a document from the system font table. |
RemoveFontResource | Removes the fonts in a file from the system font table. |
RemoveFontResourceEx | Removes a private or non-enumerable font from the system font table. |
SetMapperFlags | Alters the algorithm used to map logical fonts to physical fonts. |
SetTextAlign | Sets the text-alignment flags for a device context. |
SetTextCharacterExtra | Sets the intercharacter spacing. |
SetTextColor | Sets the text color for a device context. |
SetTextJustification | Specifies the amount of space the system should add to the break characters in a string. |
TabbedTextOut | Writes a character string at a location, expanding tabs to specified values. |
TextOut | Writes a character string at a location. |
Obsolete Functions
These functions are provided only for compatibility with 16-bit versions of Windows.
Calculating Text Width with PHP GD
I’m simply trying to get the width of a dynamic line of text for addition to an image generated with GD PHP. I’m a little unsure how though. I know how to load a font using imageloadfont(), but can I use a .ttf file? I want to know the width of text using size 12 arial font. When I try to use my ttf file I get the error «Error reading font, invalid font header.» If I need a .gdf file, where can I find a font size 12 gdf file? Here’s my code:
2 Answers 2
imageloadfont() is used to load user-defined bitmaps. If you just want to use Arial or any other TrueType fonts (.ttf) or OpenType fonts (.otf) (support for the latter in GD lib is buggy), then what you need is imagettftext() . Before using imagettftext() and writing text to your image though, you first need to know if it will fit. To know this you just need to call imagettfbbox() and pass it the font size, the angle of the text (0 for horizontal text), the path to your .ttf or .otf font file and the string of text itself and it will return an array with 8 elements representing four points making the bounding box of the text (check PHP manual for specifics). You can then reference those array elements and perform calculations in order to know the width and height that that particular string of text will take up. You can then use those values to create an image with a specific width and height that will allow for the text to be displayed in its entirety.
Here is a simple script that accomplishes what you are trying to do in order to get you started:
Change values accordingly to fit your needs. Don’t forget to read the PHP manual.
How to get Text Width
How to get Text Width
How to get Text Width
My dilemma is that the software I am using (ArcMap 8.2) does not have word wrap for its text elements. So when I have a user enter a bunch of text on a form and then when I try to place that text on a map as a text element (basically a label) the text will extend out until the end of the string is reached, which is generally a couple of inches off of the map page if they enter a paragraph.
What I would like to do is write some code that will through several iterations wrap the text based on a length that I find acceptable. I can not seem to figure out how to determine the actual width of the text given its size and font (i.e. 12 point Arial). Is there a way to get the width of a string or text in a textbox? If I can get past the width part I think I can figure the rest of the code out.
Any help would be greatly appreciated.
RE: How to get Text Width
Set Autosize of an Label to TRUE
label1.Caption = «Label1»
MsgBox Str(label1.Width)
label1.Caption = «Label 400»
MsgBox Str(label1.Width)
You will see that the wigth is changing. now you can determinate your width and you will do
for i = 12 to 8
label1.fontsize = i
if label1.width
RE: How to get Text Width
RE: How to get Text Width
If the textbox has the same font as the form then use the TextWidth method. The width is returned according to the ScaleMode setting:
RE: How to get Text Width
One can use the TextWidth and TextHeight properties to determine word wrap. If the specific control (textbox or label) doesn’t have these properties, one use the TextWidth and TextHeight properties of the form (for example, Me.TextWidth(strMyText) .)
To do word wrap, set up a loop to scan the source string for whitespace (spaces and tabs). Then add each word from the source string to a destination string until the textwidth exceeds the desired limit. Back up one word, place a vbCRLF character in the destination string and continue adding words until one hits the right margin again. Loop until done.
Sorry. I don’t have sample code handy.
Cassie
RE: How to get Text Width
Thanks everyone for the quick response. I am now starting to realize what my problem is. I am using VBA instead of VB. I am thinking that textwidth is not available in VBA? Can anyone confirm this? Thanks in advance.
RE: How to get Text Width
Good Luck
—————
As a circle of light increases so does the circumference of darkness around it. — Albert Einstein
RE: How to get Text Width
RE: How to get Text Width
Thanks for the input.
To add a report object do I assume I have to add the report control to my tool box? I have done so but the icon it adds just say OCX (doesn’t have an icon that looks to have any meaning) and gives a .dll error when I try to add it to my form? Any thoughts on this?
thanks for the information, being a relative newbie I really don’t know anything about making API calls. I’ll need to do some reading on the subject.
RE: How to get Text Width
Here you’ll have a example
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Declare Function WindowFromPoint Lib «user32» (ByVal xPoint As Long, ByVal yPoint As Long) As Long
Private Declare Function GetCursorPos Lib «user32» (lpPoint As POINTAPI) As Long
Private Declare Function ExtTextOut Lib «gdi32» Alias «ExtTextOutA» (ByVal hdc As Long, ByVal X As Long, ByVal Y As Long, ByVal wOptions As Long, ByVal lpRect As Any, ByVal lpString As String, ByVal nCount As Long, lpDx As Long) As Long
Private Declare Function GetWindowRect Lib «user32» (ByVal hwnd As Long, lpRect As RECT) As Long
Private Declare Function GetTextExtentPoint32 Lib «gdi32» Alias «GetTextExtentPoint32A» (ByVal hdc As Long, ByVal lpsz As String, ByVal cbString As Long, lpSize As POINTAPI) As Long
Private Declare Function GetWindowDC Lib «user32» (ByVal hwnd As Long) As Long
Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim Pt As POINTAPI, mWnd As Long, WR As RECT, nDC As Long
Dim TextSize As POINTAPI, CX As Long, CY As Long
‘Get the current cursor position
GetCursorPos Pt
‘Get the window under the cursor
mWnd = WindowFromPoint(Pt.X, Pt.Y)
‘Get the window’s position
GetWindowRect mWnd, WR
‘Get the window’zs device context
nDC = GetWindowDC(mWnd)
‘Get the height and width of our text
GetTextExtentPoint32 nDC, «Hello !», Len(«Hello !»), TextSize
For CX = 1 To WR.Right — WR.Left Step TextSize.X
For CY = 1 To WR.Bottom — WR.Top Step TextSize.Y
‘Draw the text on the window
ExtTextOut nDC, CX, CY, 0, ByVal 0&, «Hello !», Len(«Hello !»), ByVal 0&
Next
Next
End Sub
Private Sub Form_Paint()
Me.CurrentX = 0
Me.CurrentY = 0
Me.Print «Click on this form,» + vbCrLf + «Hold the mouse button,» + vbCrLf + «drag the mouse over another window,» + vbCrLf + «release the mouse button» + vbCrLf + «and see what happens!»
End Sub
RE: How to get Text Width
For the sake of diversity, here is another way to wrap text:
Public Function WrapText(TextToWrap As String, FontName As String, FontSize As Integer, FontBold As Boolean, Inches As Double) As String
Dim LCV As Long
Dim Words As Variant
Dim TextLength As Double
Dim TempWrapText As String
Printer.ScaleMode = 5 ‘set to inches
Printer.Font = FontName
Printer.FontSize = FontSize
Printer.FontBold = FontBold
TextToWrap = Replace(TextToWrap, Chr(13), » «)
For LCV = 0 To UBound(Words)
If TextLength + Printer.TextWidth(Words(LCV))
Red Flag Submitted
Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.
Reply To This Thread
Posting in the Tek-Tips forums is a member-only feature.
Click Here to join Tek-Tips and talk with other members! Already a Member? Login