Scrolling Overflowed DIVs with JavaScript - javascript

I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.
So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):
$("#thediv").scrollTop = $("#thediv").scrollHeight;
However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.
The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.
Any ideas guys? This one's got me stumped. Thanks!

scrollHeight should be the total height of content. scrollTop specifies the pixel offset into that content to be displayed at the top of the element's client area.
So you really want (still using jQuery):
$("#thediv").each( function()
{
// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
this.scrollTop = scrollHeight - this.clientHeight;
});
...which will set the scroll offset to the last clientHeight worth of content.

scrollIntoView
The scrollIntoView method scrolls the element into view.

Using a loop to iterate over a jQuery of one element is quite inefficient. When selecting an ID, you can just retrieve the first and unique element of the jQuery using get() or the [] notation.
var div = $("#thediv")[0];
// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(div.scrollHeight, div.clientHeight);
div.scrollTop = scrollHeight - div.clientHeight;

$("#thediv").scrollTop($("#thediv")[0].scrollHeight);

It can be done in plain JS. The trick is to set scrollTop to a value equal or greater than the total height of the element (scrollHeight):
const theDiv = document.querySelector('#thediv');
theDiv.scrollTop = Math.pow(10, 10);
From MDN:
If set to a value greater than the maximum available for the element,
scrollTop settles itself to the maximum value.
While the value of Math.pow(10, 10) did the trick using a too high value like Infintiy or Number.MAX_VALUE will reset scrollTop to 0 (Firefox 66).

I had a div wrapping 3 divs that were floating left, and whose contents were being resized. It helps to turn funky-colored borders/background on for the div-wrapper when you try to resolve this. The problem was that the resized div-content was overflowing outside the div-wrapper (and bled to underneath the area of content below the wrapper).
Resolved by using #Shog9's answer above. As applied to my situation, this was the HTML layout:
<div id="div-wrapper">
<div class="left-div"></div>
<div id="div-content" class="middle-div">
Some short/sweet content that will be elongated by Jquery.
</div>
<div class="right-div"></div>
</div>
This was the my jQuery to resize the div-wrapper:
<script>
$("#div-content").text("a very long string of text that will overflow beyond the width/height of the div-content");
//now I need to resize the div...
var contentHeight = $('#div-content').prop('scrollHeight')
$("#div-wrapper").height(contentHeight);
</script>
To note, $('#div-content').prop('scrollHeight') produces the height that the wrapper needs to resize to. Also I am unaware of any other way to obtain the scrollHeight an actual jQuery function; Neither of $('#div-content').scrollTop() and $('#div-content').height would produce the real content-height values. Hope this helps someone out there!

Related

How to change the width/height element, which has settings in subclass

I've a trouble with the style of nav element in my web application.
As you're able to see, if to focus on element nav#menu.horizontal-menu - I can see the actual width/height of that element in Chrome.
BUT! When I try to obtain that element in JavaScript by the id - menu (as you can see the tag declaration of nav tag in the bottom part of screen):
There is no both width or height values of it...
I rather understand, that it may be because of:
`nav#menu.horizontal-menu` != `nav`
But, it's only my suggestion... I've tried then to use both functions:
getElementsByClassName()
querySelector()
But... also no success as you can see in screens, what's wrong and how to get so needed actual width and height options from element?
Thanks!
I think you are looking for this answer:
How do I retrieve an HTML element's actual width and height?
.style.width only checks what is filled in in the style attribute of the element. OffsetWidth would probably work...
That's because there are no width and height styles defined for it.
To calculate the rendered width and height, use a.offsetWidth and a.offsetHeight. Those are the values that DevTools are showing on hover.
Have you tried:
var width = document.getElementById('foo').offsetWidth;
var height = document.getElementById('foo').offsetHeight;
For cross-browser compatibility I'm recommending you to use jQuery

width of dynamically inserted div containing text

I have a script that dynamically inserts a div containing text in the dom. The text content is not known in advance.
I need to know the width of this div, but it seems that that the return value of document.defaultView.getComputedStyle(node, "").getPropertyValue("width") or node.offsetWidth cannot be trusted.
I used setInterval to log it, and the value changes over time. For instance, in my case it starts with 929px and then changes to 908px.
This div is in position absolute, it has whitespace nowrap, so I don't think it is being "pushed" by other dom elements or that it somehow changes once inserted.
Is there an elegant way to retrieve the width, or do I have to use an ugly setTimeout to retrieve it once the return value is stable ?
Try:
yourDOMElement.getClientBoundingRect()
This will return an object with top, left, right, bottom, height and width attributes. This should be cross-browser.
Note: If you are going to work with the position attributes (top, left, right, bottom, height) of the returned, take into account scroll offset if necessary.
Update: To ensure this works on older browsers that don't have the width/height attribute, calculate it subtracting right/bottom from left/top.
The viewport can change its size because of the scrollbar. Once the scrollbar appears, its width can no longer be used by the document. Force the scrollbar to exist before you measure the size by adding overflow: scroll or overflow-y:scroll to the <html> element.
The size of a block-level element is, by default, its container width minus margins and padding (even if it's positioned absolutely), which is ultimately the wiewport width unless you set a fixed width somewhere along the way.
Using jQuery, you should be able to do this:
var width = $("div-selector").width();
this is fairly easy?
open the page in a browser and press f12. With firefox there is a button "inspect element" on top and in chrome it's on the bottom. Click it and hover your mouse over it. This should give you the height and width in px. Never been wrong for me.
if it still doesn't show, click it and you can see it in the css panel of the console.

Prepend a div without shifting the contents down? Using iScroll

I've got a container div with a bunch of scrollable content (for the record I'm using iScroll - if that changes the solution). When I scroll to the top I want to load content above the current scroll position. If I simply prepend the div using jQuery "prepend();" the contents in my scrollable area shift down. Ideally we'd want to keep the current content in the frame and have the scrollable area grow upwards above the content.
Any thoughts?
Thanks!
According to the iScroll website, it has a method called scrollToElement:
scrollToElement(el, runtime): scrolls to any element inside the scrolling area. el must be a CSS3 selector. Eg: scrollToElement("#elementID", '400ms')
If you always prepend a fixed amount of divs (e.g. always a single div), I imagine you could use it to scroll to (e.g.) the second element right after you've prepended the new content:
// ... (prepend new content)
myScroll.scrollToElement('#scroller :nth-child(2)', '0ms');
I haven't tried this, so please let us know if this works for you.
After a quick look through iScroll's source, here's what I've found:
The current x and y are always available through myScroll.x and myScroll.y.
iScroll has an internal function _offset(el), which returns the left and top offset of any given element.
This basically opens up two solutions:
Use _offset(el). While possible, this is inadvisable. The underscore is a convention for marking a function "private", meaning, amongst other things, that it's not part of the official API.
or
Use the newly added element's height:
var x = myScroll.x;
var y = myScroll.y;
// ... (prepend new content)
y += $('#scroller :first-child').outerHeight();
myScroll.scrollTo(x, y, '0ms');
You may need to pass true to .outerHeight(), which makes it include margins.
Once again, I haven't tested this, so please let us know if it works.

How to keep an absolutely positioned element directly over the position of inline one?

This is a follow up question to How can I stop an IFrame reloading when I change it's position in the DOM? if you want the background.
I have an inline div <div id="leaderboard-slot"></div> (with a fixed width and height) and another div ("leaderboard-loader") further down the page with the actual content for that div.
For various reasons (see previous thread), I am unable to simply do an appendChild or similar.
Instead, I'm hoping to position leaderboard-loader such that it takes up the space "reserved" by leaderboard slot. I've used some jQuery methods to do this:
var loader = $('leaderboard-loader');
var dest = $('leaderboard-slot');
var pos = dest.getPosition();
loader.setStyle('top', pos.y + 'px');
loader.setStyle('left', pos.x + 'px');
which I fire on document load and resize. However, if other elements within the page cause a reflow, then the target div moves, but the loader doesn't.
Is there a safe way of doing this - it needs to work when I know nothing else about the page (ie I can't just make this call on any other methods that might cause a reflow, because I don't know what those are).
Any help would be much appreciated - thank you :)
If I understand your question correctly, there is no need for Javascript. Just put leaderboard-loader in front of the leaderboard-slot tag, give it position: absolute and identical width and height. If slot is a normal element, loader will float above it and cover it perfectly.
<div id="leaderboard-loader"></div><div id="leaderboard-slot"></div>
I'm starting to regret my answer now. Hopefully you can find something better than the absolute positioning workaround. But, in the spirit of kludgey solutions, you could call the repositioning script on a timer. sigh.
You could put them both in the same relative positioned, 0 margin div, with the temporary div z-indexed on top of the slow loader.
Make them both absoluely positioned in the parent, not the window, at 0:0 and the same size.
You can use opacity and fade one in as you fade the other one out, or just swap visibility:hidden and visible for the two elements when you are ready..

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