Getting the height of a div, but not in pixels - javascript

Thanks for looking into this.
Basically, what I am trying to do is to get the height of a div (which is set to 100% in my style.css, so it should be resizable on any device hopefully) so that I could print numbers 1-whatever number.
So for example if the window is small it'd print out the numbers 1-45, if it's a smartphone browser, then the numbers will scale down to 1-10.
at the moment that's what it looks like:
<div id="line_numbers">
<script type="text/javascript">
var i=0;
var div_height=(document.getElementById('line_numbers').offsetHeight)/ getElementsByTagName("p").style.fontSize();
while (i < div_height) { //if i is less that the height
i++; //then increase its number
document.write("<p>" + i + "</p>"); //and print out the number and new line (<p>)
}
</script><!--end of iteration script-->
</div><!--end of line numbers-->
I understand the height var calculation is wrong but I hope you understand the logic: Got the height of the div and given that padding for every (every printed number) is 5px and the height of the font of every number, I can divide the height by the font size+10px (upper and lower padding).
When I try to print out the div_height variable nothing happens and I am a bit confused.
Thank you for taking time, again.
blagie-bla

It looks like you got what you came for, but here's a heads-up to supplement the answers above: Consider using element.style.lineHeight instead of element.style.fontSize, as only the former multiplied by the number of lines will give you the actual height of the div, (or an accurate line-count given height \ line-height).

Related

Set large value to div's height

I have a problem with height limitation of <div></div> in some web browsers, like Firefox. I have javascript code like this:
$('#MyDiv').css("height","20000000px"); // 20,000,000 pixel height
But I see height: 2e+7px; rule in the firebug. This problem exist in IE too, But in google chrome everything is ok and I see height: 20000000px;. How can I set very large value to div's height in a way that works for most browsers?
EDIT: firefox has no scrollbar in this div, but google chrome has scrollbar.
I want just confirm the problem which describes hamed. One can try the demo http://jsfiddle.net/OlegKi/y4tLxx53/4/ which contains setting height property using jQuery.css on the test div:
var testValues = [10000, 1533916, 1533917, 1533918, 10737418, 10737419,
17895696, 17895697, 17895698, 20000000], h, i;
for (i = 0; i < testValues.length; i++) {
h = testValues[i] + "px";
$("#test").css("height", h);
$("#log").append("<span>After setting height " + h +
", one have height: " + $("#test").css("height") +
"</span><br/>");
}
with very simple HTML markup
<div id="log"></div>
<div id="test"></div>
One can see in Google Chrome the expected results
but Firefox shows
and IE10 and IE11 displays
instead.
By the way, the setting of large height on divs will be used to implement "virtual scrolling" (for example in jqGrid). So that the user sees div with large scroll and a table inside. If the user uses scroll bar then the page of data will be downloaded from the server via Ajax. In the way the height of the div should corresponds to the size of data on the server. If one row of table data have height 23px, then IE10/IE11 can simulate in the simple way only 66692 rows of virtual data in IE (1533916/23=66692) and 778073 rows (less as a million rows) in Firefox. The demos shows that one need use more sophisticated implementation of "virtual scrolling" to have no, described above, problems with setting of height of div.
One can use the same inline demo alternatively:
var testValues = [10000, 1533916, 1533917, 1533918, 10737418, 10737419,
17895696, 17895697, 17895698, 20000000], h, i;
for (i = 0; i < testValues.length; i++) {
h = testValues[i] + "px";
$("#test").css("height", h);
$("#log").append("<span>After setting height " + h +
", one have height: " + $("#test").css("height") +
"</span><br/>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div id="log"></div>
<div id="test"></div>
I have run into the same issue implementing virtual scrolling. My solution is to detect numbers that are too large and use a multiplier.
This means that the height of the overflowed content will be realHeight / multiplier. And when I'm trying to figure out what data to show, I just take the scrollTop * multiplier. This works fine to the user because the scrollbar has a minimum height.
This will work if you have control over the effect. I'm not familiar with jqGrid, but the source code may have to be updated.
That's not a problem. The value 2e+7 is the same as 20000000, it's just a different way of showing the number.
In some tools, large numbers are shown in scientific notation. The number 2e+7 means 2 * 107.
If your document is size is not fixed, you can use this:
var height = $(document).height();
and set your div container height accordingly
$('#MyDiv').css("height",height);
This should work on all the browsers

Javascript function is stopping after a certain line

I am trying to create a javascript function that crops and centers image to 1000px. To do that, I take the width, subtract 1000, divide by 2, and multiply by -1. I then take this value and assign it to margin-left and margin-right. I have it set to run on page load. For some reason, it is not executing my first line of code. Take a look below. (debug alerts are for debug purposes)
Javascript
function crop()
{
alert("debug")
width = document.getElementById(slide).width
alert("debug")
width = -1((width - 1000)/2)
alert("debug")
document.getElementById(slide).setAttribute("style","margin-left" + width + "px")
alert("debug")
document.getElementById(slide).setAttribute("style","margin-right" + width + "px")
alert("debug")
}
This is the element I am trying to get it to apply all this to.
Element
<div id="mySlides" style="width:1000px; overflow:hidden;">
<img src="img/1.jpg" onclick="slideshow()" id="slide" />
</div>
As you can see, it only displays the first debug alert, and doesn't display anything else after that. Can somebody explain why it is ignoring the rest of the code?
slide is a reference to a variable named slide. You probably want "slide" (a string), as your img element has id="slide".
You should spend some time getting familiar with your browser's debugging tools (alert() is a horrible way of debugging). It would have pointed out...
ReferenceError: slide is not defined
You are missing delimiters around the string here:
width = document.getElementById("slide").width;
You are missing the multiplication operator here:
width = -1 * ((width - 1000)/2);
You are missing the string delimiters, and colons in the style declarations, and also you have to put the styles together otherwise the second one will overwrite the first:
document.getElementById("slide").setAttribute("style","margin-left:" + width + "px;margin-right:" + width + "px");

Javascript DOM offsetHeight issue on small screens

I have a simple code to set the height of one column, id="colLeft" to the height of another column, id="colRight", with no padding or borders:
<script type="text/javascript">
var colLeft = document.getElementById("colLeft");
var colRight = document.getElementById("colRight");
colLeft.style.height = colRight.offsetHeight + "px";
</script>
This code works fine on desktop and iPad, but on my android phone the results are rather unpredictable. Sometimes colLeft is much longer, sometimes colRight, and sometimes it works the way it should. I have tried it on two browsers with the same results.
I have also tried it inside window.onload=function(){...} which gave slightly less variance in the results, but is still not perfect.
Thanks for any help.
You can read a bit about offsetHeight here. The important thing to note is that if the content is larger than the viewable area the browser might do funny things with non-scrolling elements. Because this is a phone browser, I am guessing that the issue is that it is miscalculating the column height because it doesn't deal with scrolling elements correctly.
How do you set the height of the first column? If it has a valid height set in the style sheet you could easily do something like this:
colLeft.style.height = colRight.style.height;
If that doesn't work, you may need to set the column height based on the browser window size with something like:
colLeft.style.height = colRight.style.height = (window.innerHeight - 10) + "px";
Or something similar.

How to fit a serie of div's into the size of the window?

I have a number of divs (ranging from 2 to 80) that are loaded into my html as inline-blocks.
The width of these divs are designed to fill up the entire space of the window width (like a single bar) minus the margins of the div (data.length*2) and minus the padding -20 depending on a variable that's generated through tag.duplicate_count/full_links.length.
So far so good
var tag_width = tag.duplicate_count/full_links.length;
tag_width = ($(window).width()-(data.length*2)-20)*(tag_width);
Result:
|__||__|_______|___|_______________|
<--------------- window.width --------------->
The piece of code above actually works but here's where the problem starts. Some div's sometimes get a width assigned that's smaller then 10px.
To fix this I've put this in my code:
tag_width = tag_width < 10 ? 10 : tag_width;
Result:
|__|__|_|_______|___|______________
___|
<--------------- window.width --------------->
However the total width of all the divs combined gets larger then the width of the screen and it will start to make a second bar (WHICH I REALLY DON'T WANT!). I know why but I want to prevent it. Is there anyone who can help with this problem, has encountered this problem or knows the answer?

Why is this while JavaScript loop infinite?

I hate doing this. This is THE small piece to end a large project and my mind is fried...
Here's the code. It checks to see if an element is overflowing and resizes the font. It is supposed to resize it until it doesn't overflow. The condition for the loop seems to be ignored and the browser freezes... I feel that I'm missing something crucial in how jQuery works here.
$.fn.fontBefitting = function() {
var _elm = $(this)[0];
var _hasScrollBar = false;
while ((_elm.clientHeight < _elm.scrollHeight) || (_elm.clientWidth < _elm.scrollWidth)) {
var fontSize = $(this).css('fontSize');
fontSize = parseInt(fontSize.substring(0,fontSize.length-2))*0.95;
$(this).css('fontSize',fontSize+'px');
}
}
Thanks in advance.
Change:
fontSize = parseInt(fontSize.substring(0,fontSize.length-2))*0.95;
to:
fontSize = parseInt(fontSize.substring(0,fontSize.length-2))-1;
Here's a Working Demo. When the font size reached 10px, 10*.95 was 9.5 which the browser was rounding up to 10px. Thus infinite loop.
You need to step through your code in a debugger and actually check your condition values to make sure they are changing how you expect. My guess is _elm.clientHieght and _elm.clientWidth aren't actually changing.
var fontSize = $(this).css('fontSize');
fontSize = parseInt(fontSize, ...
The unit you get from font-size is not necessarily (a) pixels, nor (b) the same unit as you put in.
It's not specified what unit is used to return the length, but in many browsers it is currently points. Since points are smaller than pixels, the integer length will be longer, so you can quite easily keep on *0.95ing it forever.
Even if it were pixels, the browser could round the size up to the nearest pixel, making 95%-size the same size as 100% when you read it back. Or you could hit the minimum-font-size setting and you wouldn't be able to reduce it any more.
So instead of reading the current font size back on each step, keep the pixel size you want in a variable and reduce that variable each time. Then if you reach a predetermined lower bound for the value of that variable, give up.
You are probably running into an endless loop because the font size doesn't actually change. E.g. if the font size found is 10px you will update it to become 9.5px which is probably rounded back to 10px by the browser. In that case nothing changes and the function will keep running forever.
You've got an unrelated problem when you do
$('div').fontBefitting()
This will make the text in the first div fit it's box, then make the font size of all the other divs the same as the first. This does not sound like intended behaviour. You would hope that it would make each div resize its text and only its text to fit.
You need to change your code to this:
$.fn.fontBefitting = function() {
/* $.fn.* runs on a jQuery object. Make sure to return it for chaining */
return this.each(function() {
var fontSize = parseInt($(this).css('fontSize'));
while (this.clientHeight < this.scrollHeight ||
this.clientWidth < this.scrollWidth) {
fontSize--;
$(this).css('fontSize', fontSize + 'px');
}
});
}
You're checking to see if the clientHeight or clientWidth are LESS than the scrollHeight or scrollWidth, and if they are you are REDUCING the font size? It will never converge under those circumstances. You want to INCREASE the font size.

Categories

Resources