Finding width of text in Javascript [duplicate] - javascript

This question already has answers here:
Calculate text width with JavaScript
(29 answers)
Closed 10 years ago.
Is there a way to find the width of text in Javascript (jQuery is used, so happy to take advantage of any functions they provide) for a hidden element?
I want to have a graph of nodes. Each node has text inside and I want the nodes to have a width that accommodates the text up to a limit. So I essentially create hidden <div>'s with some html inside. Then I use jQuery to display those <div>'s on the graph at the right spots. It's important that I know the correct width ahead of time so I can construct the graph properly.
UPDATE: Just to clarify, I need to know how wide some text is while it's hidden. Blender gave an answer below, I'm hoping there's a less tricky way?

What width do you mean? If you mean the <div> element's width, there's a handy function which does just what you need. Play with some of these:
$('#foo').width();
$('#foo').innerWidth();
$('#foo').outerWidth();
As for finding the width of a hidden element, I usually do this dirty trick:
var zIndex = $('#foo').css('z-index');
$('#foo').css('z-index', '-10');
$('#foo').css('position', 'absolute');
$('#foo').css('display', 'block');
var fooWidth = $('#foo').width();
$('#foo').css('display', 'none');
$('#foo').css('z-index', zIndex);
There must be a simpler way, though...

$('#txt').width()
http://jsfiddle.net/Detect/jk97D/

You can set the style of the divs to have no wrap white-space:nowrap (so, text is in one line) then get the width of each div, if more than the limit, set it to the limit and set the style to allow text wrapping `white-space:normal

Just throwing in a non-JQuery answer to this. Assume I have a work div with id myworkerdiv and i have put my text in already.
var myDiv document.getElementById('myworkerdiv'),
width = myDiv.clientWidth || myDiv.scrollWidth;
You can also find out height as well, if your so included (clientHeight || scrollHeight).

You could use something similar blender's method, but use the visibility css property rather than display. Visibility:hidden; keeps placement of the element, but just makes it invisible.

Related

Position an element at the bottom of a floating div with unknown height

I am currently trying to position an element in a way that it always is at the bottom of it's parent. What's special here is that none of the heights or widths are known. I'd like to do this without tables, if at all possible (my superior is against using those. In a very religious way).
I tried the approach of using position:relative on the parent and position:absolute; bottom:0; on the box I want to have at the bottom. This, however, causes the box to overlap with the other content of the parent div since absolute positioning causes the parent to ignore the height of the positioned element. Some JavaScript is used to align the heights of the floating divs to each other. But disabled JavaScript should not completely break the layout (as in: cause content to overlap or break the "flow" of the page).
Here's the fiddle with the exact structure of my markup: http://jsfiddle.net/vbeC2/27/
I did read the "float: bottom" question on SO, but none of the answers really adressed my problem, hence the new question.
It's not the cleanest solution, but since you were already using the maxHeight bit to calculate the sizes, I just added a second each loop to check the max-height of the bottom section, and added it, so that the relative, absolute positioning would work.
http://jsfiddle.net/robsterlini/svcGB/ or http://codepen.io/robsterlini/pen/BcDyt
EDIT When you resize your browser it won't work, but you could just add a resize event that recalculated it, and you'd need to think about creating some javascript-less fallbacks, either using modernizr, or just some simple
Please find the working demo here: JS Enabled
Modified the jquery logic to calculate the height of the maximum height of the container as shown below:
$(document).ready(function(){
//Set the height of the columns to the highest value of all columns
var maxHeight = 0;
$(".same-height").each(function(){
var k = $(this).children('.headline').innerHeight() + $(this).children('.description').innerHeight()+$(this).children('.bottom').innerHeight();
maxHeight = Math.max(maxHeight,k);
});
$(".same-height").css({"height" : maxHeight});
});
If JavaScript is disabled then you should apply different styles as shown in demo here:
JS Disabled
Here is something similar to what you want to atchive but the demo is centering the
http://css-tricks.com/centering-in-the-unknown/
You should use the same trick : using css ::after/::before pseudo classes to set your footer content in your parent div

Is it possible to use jQuery to find height of a span of text with an undefined height?

I have a <span> of text that isn't defined by height. The text inside is inserted dynamically and varies from each instance of this span to the other. Is there any way to use jQuery to find the height of this span?
Here's what I've tried:
parseInt($('span.tag_title', container).outerHeight(true), 10)
But that doesn't return anything unless I define the span in CSS?
Anyone know how to fix this?
seems to work... you don't need to parse the value though. outerHeight returns an int. Here's a demo: http://jsfiddle.net/V6Gx6/show
Just resize the window.

Dynamically increasing textbox height? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Autosizing Textarea
Hello all, I am trying to solve a problem and getting absolutely no where with it. What I am trying to do is dynamically change the height of an inputbox when the users text overflows it's width (sorta like Facebook's status update textbox).
You enter a brief update, and if the text is longer than the textbox, it creates a new row. I tried using a textarea, but for whatever reason cannot force it to be exactly 1 row by default.
Anyone know an easy way of doing this? :(
You can manually control the size of the textarea using the CSS height and width parameters. By binding a keypress event to the textarea, you can get the amount of text in the box and adjust the height accordingly. For example, here's some jQuery that will add 20 pixels to the height of the box for every 50 characters you put in:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<textarea id="textbox" style="height:20px;width:400px;"></textarea>
<script type="text/javascript">
$(document).ready(function() {
$("#textbox").val('');
$("#textbox").keypress(function() {
var textLength = $("#textbox").val().length;
if (textLength % 50 == 0) {
var height = textLength/50;
$("#textbox").css('height', 20+(height*20));
}
});
});
</script>
You can tweak the values to get the desired effect.
To get the textarea to stretch, give this a go (jQuery): http://www.unwrongest.com/projects/elastic/.
As for the height of exactly one row, you could try rows="1" in the <textarea> tag, as well as removing CSS styling. Some browsers, however, may set a textarea's minimum height to more than one row.
Another solution would be to use a div on screen that, when the user clicks on it, makes the browser focus on a hidden textbox. The user types into the hidden text box, and the div is given the textbox's contents via. JavaScript. The tricky bit then is getting the flashing cursor, but you could use the pipe | character in the div and make it flash, although this starts getting long winded about the time you start it. I'd try with the textarea again personally :-)
Hope this helps,
James

JavaScript: Check width of a <div> object before placing it

Consider:
$("#PlotPlace").append('<div style="position:absolute;left:200px;top:40px;font-size:smaller">Hello world!</div>');
I need to execute that line only if the width of the resultant text would be less than 60px. How can I check the width before placing the object?
Unfortunately, the div will only have a width value once it is rendered into the DOM.
I would append that content to an inconspicuous area of the document, perhaps even absolutely positioned so that no flow disruption occurs, and make sure that it is set to "visibility:hidden". That way it will be inserted into the DOM and be rendered, but be invisible to the viewer.
You can then check the width on it, and move it into position and set it to "visibility:visible" at that point. Otherwise, you can remove it from the document.
Maybe you can append it invisible, then check it's width, and then consider to show or hide.
$("#PlotPlace").append('<div style="position:absolute;left:9001px;top:40px;font-size:smaller">Hello world!</div>');
var div = $('#PlotPlace').children("div");
if(div.width() < 60)
div.css({left:200})
Sounds like something you'd have to hack. I don't believe the JavaScript runtime in any browser has an event you can hook into in between calculating the layout and displaying the element, so you can add it in a way that it can't be seen and doesn't affect the height (doesn't cause additional scrolling), and then show/hide it based on the width at this point. It's hacky and ugly, but because you don't have many event hooks it might be the only way to do it.
You can´t. At least not so easy. The text you insert is written in a specific font, which must be rendered by the browser, then you know the width of the element. By the Way, what exactly do you want to insert, with such a restriction? Wouldn´t it be simpler to cut the text within the output parameters?

Javascript clientHeight and alternatives

I am currently trying to modify a Javascript function that "slides in" a <div>. The script as it is requires you to define the height of the div, so it is mostly useless in dynamically filled <div>s. I found some text on the clientHeight property in javascript, but it would appear that it doesn't support <div>s with display set to none (which is the method used to slide the div in). That makes sense, as the height of that div in the client window is nothing.
Basically I was wondering what other methods you all know of, or if there's a way to get around the clientHeight = 0 when display: none.
Thanks!
Oh, and here's the function I'm using:
function getDivHeight(objName) {
return boxHeight = document.getElementById(objName).clientHeight;
}
A simple solution is to set it's visibility to "hidden" and it's display to "block" and measure it. However, some modern browsers will manage to update the page layout during this short time and you will get a nasty flicker. The easiest way to overcome this is to place the element in an absolutely positioned container with overflow set to "hidden".
I've had luck cloning the element, moving it offscreen, then displaying it to get the client height:
var original = document.getElementById(some_id);
var new_item = original.cloneNode(true);
document.body.appendChild(new_item); // item already hidden, so it won't show yet.
// you may wish to validate it is hidden first
new_item.style.position = "absolute";
new_item.style.left = "-1000px";
new_item.style.display = "block";
var height = new_item.clientHeight;
EDIT: Looking through the jQuery code, they do exactly what Tsvetomir Tsonev suggests. jQuery temporarily sets the style to "display: block; position: absolute; visibility: none", and then measures the height, swapping the properties back after the measurement.
So, it looks like you're stuck with having to do something hackish, whether it's cloning the node or risking having it flicker in some browsers... I like Tsvetomir's suggestion better than my initial hack as it, at least, doesn't involve cloning a node into the DOM that you don't need. Either way, the element must not be set to "display: none" in order to measure it's height. Isn't the DOM wonderful? :-)
EDIT 2: Also worth noting that, after jQuery gathers the height, it adds allowances for padding, margin and border sizes, so you may need to as well.
Yes, an element that is not displayed on the page has no dimensions.
It kind of makes sense. Consider an element that has been created and filled with a bunch of text, but not yet added to the document tree. How high is it? Depends on font-size. How big is font-size? Depends where in the document that div is inserted; its parent font-size would inherit through.
Similarly for an element with “display: none”. It's not rendered, so it has no dimensions. Couldn't we ask “how high would this be if it were ‘display: block’”? Turns out no, because if it were displayed, that in itself could change the dimensions of its parent block, and then the dimension of displayed elements would be inconsistent with the dimensions of non-displayed elements!
The typical solution is to unset “display: none”, measure the height of the element, and then immediately re-set “display: none”. The browser won't redraw in the middle of a bit of JavaScript, so you won't see a flicker on the page.
I nkow you guys solved this a long time ago but I thought I should share this since it quite tricky to get the height of a hidden div tag.
heres what I did after reading your post,
I placed the div i want to slide inside a 1px height div with overflow set to hidden.
you dont even need to set the display of the inner div to none since it is already there and if you use offsetHeight it should return the proper height for all browsers and you can use that height to slide your div up an down.
PEACE!!!
In IE you could try scrollHeight, but I'm not sure if it will work or if it is cross browser.

Categories

Resources