I'm trying to calculate the number of characters that fits in one line of a div and trim off the rest although text-overflow is an option I rather calculate the length of the string that fits in it properly. Is the font-size of a character almost equal to it's width, if not how do you calculate it's width including the text spacing and the width of a white space.
P.S. - Before flagging this question, do know I've went through most of the questions and answers and none of them were satisfactory.
One way I would do it is to check if there's enough space left in the div. To do this, you would need to create an identical div and slowly remove one character from the cloned div until the original div is bigger or equal in width to the cloned div.
divClone.textContent = text
document.body.appendChild(divClone)
while(divClone.clientHeight > originalDiv.clientHeight) {
divClone.textContent = divClone.textContent.substring(0, divClone.textContent.length-1)
}
originalDiv.textContent = divClone.textContent
You can then delete the cloned div when it's done
Related
I currently have a draggable width container with some children.
Since its width is draggable once the width is small enough that say for example only 3 elements can fit.
Expected outputs are (0), (1), and (+4) (Number of elements that overflow + 1).
Other cases: Here only two elements fit, and 4 overflows.
The expected output is two circles with (0) and (+5).
I saw other posts where they use a fixed width and calculate the number of elements that can fit from that. However, in my use case, the width is varying and I need to get the number of elements that can fit/overflow dynamically. How can this be done using javascript and plain CSS?
var popupDiv = document.getElementsById("container")
let count = Math.round(window.getComputedStyle(popupDiv).width/widthOFElement)
I hope this help. here the widthOFElement is the width of round element. and you can add this in dragabble event listener.
Having trouble finding a solution to this. I've got a "button" div 100px wide and 30px tall with a variable label. I want the font size to shrink itself so that the entire label text is always visible.
JS or CSS solutions both work for me, just no jquery.
In flash I solved this problem by checking the number of lines of text, if it's over 1 shrink the font size until it all fits in one line. Not sure if that's possible in javascript.
Edit: Not a duplicate, that person had a variable sized container so different solutions were possible.
One thing here you can do is get the label text into similar size of the div with following CSS attributes and then count it's scrollwidth, then write a javascript loop and decrease font-size by some pixels till you find it's scrollwidth is less than your desired width.
white-space: pre;
overflow-x: scroll;
Small Javascript code which I tried
// dummy divelement
var divElement = document.getElementById('#myelement')
var fontSize = 15; // Starting from 15
while(divElement.offsetWidth < divElement.scrollWidth) {
divElement.style.fontSize = fontSize + "px"
fontSize--;
}
Does this answer your question? or should I provide you whole example?
i try make book paging.
div height is 100px.
div have a long text. text is very long long string(2mb).
i want know text subString position.
how to know text length until 50px height??
There should be a different approach
You can get the div width.
var width= getWidth();
Calculate how many character in a row (calculate manually), based on that width. And get the row number within 50px.
var limit = getRowLimit();var n=getNRow();
Do a substring.
var subtext= mytext.substr(0,limit * n);
I have a div that contains a variable amount of text, and a fixed height. Without a fixed width, the width would automatically be 100%. I could estimate the width that the div would need to be, but since the text will not always be the same, this will not always work. It would need to automatically be determined each time. Basically, I want the width of the div to be determined by the content.
Simply, my div would be something like
#a {
height:100px;
width:?;
}
Consider these: http://jsfiddle.net/ZE4Sy/2/
This is essentially what my goal is (though I did this by estimating the widths). Each div has a fixed height, but a different amount of text. I made the widths as small as they could be before the text began exceeding the height.
I only have a very basic knowledge of jquery/javascript, but I'm assuming that if there is a solution to this, it may involve those.
Thank you for your help!
Here:
$('.box').each(function () {
var $box = $(this),
width = $box.width(),
$inner = $box.wrapInner('<div></div>').children().first();
while (width > 0 && $inner.height() < $box.height()) $box.width(--width);
$box.width(++width);
});
Live demo: http://jsfiddle.net/ZE4Sy/6/
I had a similar issue but in my case there were two factors that prevented Šime Vidas' solution from working, which were that the content in my div contained HTML (p tags with margins, etc), and I wanted the div to protrude outside of the available width of the containing div if necessary. Using his solution for inspiration, I came up with this:
$('.box').each(function () {
$box = $(this);
$inner = $box.wrapInner('<div></div>');
while ($inner[0].scrollHeight > $box.height()) $box.width($box.width()+100);
});
Which simply keeps widening the box a little until the height of the inner div doesn't overrun the containing one. You could reduce the +100 figure to get a more accurate width, at the expense of processing time.
Basically I need the width of a span. Do to the need to use several custom characters that are not found on a keyboard I am building my own "input" field, using a "div". Each character gets wrapped in a "span" tag that has an event listener attached. This will allow the user to click anywhere in the string and have the cursor move to a position after a character, it also allows them to add or delete characters in the middle of a string.
I am using "offsetLeft" and "offsetWidth" to find the right side of a character, the problem is when a character/span is clicked the "offsetWidth" is way off. So for example, if I am using a 14 pixel font an "M" will return as 35 pixels wide when it is actually 11 pixels. And there are several variations, an average sized character like an "S" will return at 26 pixels when it is actually 9. So there is variation in the sizing. Now you may wonder how I found the actual letter size and that was using Firebug. Which if Firebug can find it I would assume so can I, I just haven't figured out how. So I hope someone here knows.
I also tried using "getComputedStyle" and "currentStyle to find the width and it returns "auto". Also tried getBoundingClientRect().width it the same as offsetWidth, the difference being that it also finds the fractions of a pixel in width, so an "M" is 35.366668701171875 pixels wide, odd.
EDIT:
Based on user1289347 post I should have noted that the "offsetWidth" causes the "offsetLeft" to be off by the errant amount as well.
Try jquery width() it computes the dom width pretty well every time I've used it. http://api.jquery.com/width/
And if jquery is out of the question
Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.
HTML:
<div id="Test">
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</div>
CSS:
#Test
{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
}
JavaScript (fragment):
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px";
This will create a seperate testable div with your test, credit here Calculate text width with JavaScript It's a lot of work but it should get you better results by operating outside of your existing markup.