Auto-scroll to the bottom of a div - javascript

I have a div with overflow set to scroll which essentially streams data line by line off a file. I'd like to scroll automatically to the bottom of the div whenever the stream overflows, but without using a "Click here to scroll to bottom" button.
I already know of the scrollTop = scrollHeight solution, but that requires some kind of event trigger on the client's side. I don't want this element to be interactive; it should scroll by itself.
Is there any way to achieve this?

A lot of the scrollHeight implementations didn't work for me, offsetHeight seemed to do the trick.
Pretty sure that scrollHeight tries to move it to the bottom of the height of the static element, not the height of the scrollable area.
var pane = document.getElementById('pane');
pane.scrollTop = pane.offsetHeight;

There's no way to automatically scroll an element to the bottom. Use element.scrollTop = element.scrollHeight.
If you don't know when the element is going to resize, you could add a poller:
(function(){
var element = document.getElementById("myElement");
var lastHeight = element.scrollHeight;
function detectChange(){
var currentHeight = element.scrollHeight;
if(lastHeight != currentHeight){
element.scrollTop = currentHeight;
lastHeight = currentHeight;
}
}
detectChange();
setInterval(detectChange, 200); //Checks each 200ms = 5 times a second
})();

Some old code of mine with a running example that will stay at the bottom when new content is added, if the user scrolls it will not more it to the bottom.
var chatscroll = new Object();
chatscroll.Pane =
function(scrollContainerId)
{
this.bottomThreshold = 25;
this.scrollContainerId = scrollContainerId;
}
chatscroll.Pane.prototype.activeScroll =
function()
{
var scrollDiv = document.getElementById(this.scrollContainerId);
var currentHeight = 0;
if (scrollDiv.scrollHeight > 0)
currentHeight = scrollDiv.scrollHeight;
else
if (objDiv.offsetHeight > 0)
currentHeight = scrollDiv.offsetHeight;
if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)
scrollDiv.scrollTop = currentHeight;
scrollDiv = null;
}

Related

getBoundingClientRect() showing different values on load vs scroll

I'm working on a site for a client and trying to implement custom parallax functionality. I have used the following code -
var inView = function(element) {
// get window height
var windowHeight = window.innerHeight;
// Get Element Height
var elementHeight = element.clientHeight;
// get number of pixels that the document is scrolled
var scrollY = window.scrollY || window.pageYOffset;
// get current scroll position (distance from the top of the page to the bottom of the current viewport)
var scrollPosition = scrollY + windowHeight;
var elementPosition = element.getBoundingClientRect().top + scrollY;
var elementScrolled = elementPosition + element.clientHeight + windowHeight
// is scroll position greater than element position? (is element in view?)
if (scrollPosition > elementPosition && scrollPosition < elementScrolled) {
return true;
}
return false;
}
// Get all the elements to be parallaxed
const parallaxElements = {
element: document.querySelectorAll('#header-image img'),
ratio: 0.25
}
// The parallax function
const parallax = elements => {
let items = [...elements.element],
itemRatio = elements.ratio
if ('undefined' !== items && items.length > 0 ) {
items.forEach( item => {
if ( inView(item) == true ) {
item.style.transform = 'translate3d(0, ' + (itemRatio * (window.innerHeight - item.getBoundingClientRect().top)) + 'px ,0)'
}
})
}
}
//If element is in viewport, set its position
parallax(parallaxElements)
//Call the function on scroll
window.onscroll = () => {
parallax(parallaxElements)
}
It's working ok except that when the page is loaded initially and the user starts scrolling, the position of element (#header-image img in this case) changes abruptly. I did some digging and noticed that the value of getBoundingClientRect().top is causing the issue.
When the page is loaded, it has some value, and as soon as the user starts scrolling, it abruptly changes to another value.
I am not able to figure out why this is happening. getBoundingClientRect().top is supposed to get the value of element from top of viewport, right?
Any help is greatly appreciated. Thanks!
Pls check the screenshot of inspect element here -
https://i.stack.imgur.com/RYDvK.jpg

scroll page content to custom position on mouse scroll

I want scroll page content on mouse scroll.
I have 5 images in page, at a time i want to show one image per screen.
If i scroll down second image showed be shown, if i scroll up previous image should be shown. Like wise until the last image.I have tried an example but have no idea how achieve this.
JavaScript:
var winHeight = $(window).height();
var prevHeight = 0;
var scrollCount = 0;
var docHeight = $(document).height();
$(document).ready(function(){
$(window).scroll(function(e){
console.log("in scroll top");
var top = $(window).scrollTop();
console.log("top - "+top);
if(top !=0 && top != docHeight){
if(top > prevHeight){
scrollCount = scrollCount+1;
}else{
scrollCount = scrollCount-1;
}
console.log("scroll count="+scrollCount);
$(window).scrollTop(winHeight*scrollCount);
prevHeight = top;
if(scrollCount < 0){
scrollCount = 0;
}
e.preventDefault();
}
});
My example is here http://jsbin.com/iwOsiFIY/1/
Just set the margins to what you want them to be for each image in CSS. Or a workaround is adding a bunch of "p" tags in HTML without actually adding a paragraph, The first way is the best. You might also need some JavaScript for resizing.

jQuery addClass based on how far scrolled

I have written some jquery to calculate the height of 4 elements by css class and get their height, then compare the height to how far the page has been scrolled. If the page has been scrolled to or past each element then a css class is added which animates the element.
The problem that I am having is that the jquery is adding the classes to all of the elements as soon as the page is scrolled to the first element, instead of adding the class to each as it is scrolled to.
What is wrong with my jquery that it is doing this?
Here is the jsfiddle http://jsfiddle.net/94kP6/7/
This is the jquery part of the code
// element animation scroll detection
(function ($, document, undefined) {
var animation1 = $('.animation1').height();
var animation2 = $('.animation2').height();
var animation3 = $('.animation3').height();
var animation4 = $('.animation4').height();
$(window).scroll(function() {
var winTop = $(window).scrollTop();
if(winTop >= (animation1)){
$('.animation1').addClass("animate-from-left");
}
if(winTop >= (animation2)){
$('.animation2').addClass("animate-from-right");
}
if(winTop >= (animation3)){
$('.animation3').addClass("animate-from-left");
}
if(winTop >= (animation4)){
$('.animation4').addClass("animate-from-right");
}
});
})(jQuery, document);
var animation1 = $('.animation1').height();
var animation2 = $('.animation2').height();
var animation3 = $('.animation3').height();
var animation4 = $('.animation4').height();
needs to be
var animation1 = $('.animation1').offset().top;
var animation2 = $('.animation2').offset().top;
var animation3 = $('.animation3').offset().top;
var animation4 = $('.animation4').offset().top;
or some variant for personal preference, like this:
var animation1 = $('.animation1').position().top - $('.animation1').height();
var animation2 = $('.animation2').position().top - $('.animation2').height();
var animation3 = $('.animation3').position().top - $('.animation3').height();
var animation4 = $('.animation4').position().top - $('.animation4').height();
Here's a fiddle to show you need to use .offset().top instead of .height
http://jsfiddle.net/94kP6/10/
When you use height, you are asking the scroll to wait until the height of the object instead of waiting for the top position of the object
Just change your heights to offsets
UPDATE
http://jsfiddle.net/94kP6/14/
This makes it so the animation can be seen more in the middle of the screen. Just subtract a specified height (in this case, the height of the object) from the offset and it will animate at a higher scrollTop.
You can also do the same thing, only backwards by ADDING a specified amount to the var winTop = $(window).scrollTop(); line, line this: var winTop = $(window).scrollTop() + 250;

How can I inject a div into a webpage that moves on window resize?

Essentially, I'm creating a custom click & drag selection box. The problem is that the div is position absolutely, so it will scroll with the page, but it will not move with the page when the window is being resized. My attempted solution was to listen to the window resize, and move the div according to the change. The problem is that it will SEEM to work, but it will not move entirely accurately, so it will slowly move out of place if the window is resized slowly, or quickly move out of place if the window is resized quickly. It seems that the resize listener does not capture every resize event. I've narrowed the code down to the concept I'm using.
Try injecting this script into a page (I'm using the Chrome console and I haven't made any attempt for cross-compatibility because this will be used in a Chrome extension). It will attempt to resize only when the scrollbar is not active, to replicate the behavior of the page content. The client and scoll variables are interchangeable for recording the change in dimensions, but they are both there for testing purposes. I would love to see a solution which solves this problem using styling attributes. Thanks for your help!
var div = document.createElement("div");
div.style.position = "absolute";
div.style.backgroundColor = "#000";
div.style.width = div.style.height = div.style.left = div.style.top = "200px";
document.body.appendChild(div);
// get the highest z index of the document
function highestZIndex() {
var elems = document.getElementsByTagName("*");
var zIndex = 0;
var elem, value;
for (var i = 0; i < elems.length; i++) {
value = parseInt(document.defaultView.getComputedStyle(elems[i], null).zIndex, 10);
if (value > zIndex) {
zIndex = value;
elem = elems[i];
}
}
return {
elem: elem,
zIndex: zIndex
};
}
// set the div on top if it is not already
var highestZ = highestZIndex();
if (highestZ.elem != div) div.style.zIndex = highestZ.zIndex + 1;
// last width & height of client & scroll to calculate the change in dimensions
var clientWidth = document.body.clientWidth;
var clientHeight = document.body.clientHeight;
var scrollWidth = document.body.scrollWidth;
var scrollHeight = document.body.scrollHeight;
// move the div when the window is being resized
function resizeListener() {
var _clientWidth = document.body.clientWidth;
var _clientHeight = document.body.clientHeight;
var _scrollWidth = document.body.scrollWidth;
var _scrollHeight = document.body.scrollHeight;
// horizontal scrollbar is not enabled
if (_scrollWidth <= _clientWidth) {
div.style.left = parseInt(div.style.left.replace(/px/, ''), 10) + (_scrollWidth - scrollWidth) / 2 + 'px';
}
// vertical scrollbar is not enabled
if (_scrollHeight <= _clientHeight) {
div.style.top = parseInt(div.style.top.replace(/px/, ''), 10) + (_scrollHeight - scrollHeight) / 2 + 'px';
}
clientWidth = _clientWidth;
clientHeight = _clientHeight;
scrollWidth = _scrollWidth;
scrollHeight = _scrollHeight;
}
window.addEventListener("resize", resizeListener);
PS: Please, no jQuery solutions.
Since the resize listener isn't quite dependable with outside events, I've developed a simple "hack" to get the wanted results. The window overflow is forced to scroll and the body width & height are set to +1 so that the scrollbar is active, in which the div will then stay in place. Once the resize is complete, the overflow and body dimensions are restored. This may not be a desired solution for others who want the div to move on a manual window resize, but I am invoking the resize from JavaScript so it works perfectly for me.
The script in practice:
var overflow, overflowX, overflowY, bodyWidth, bodyHeight;
function startResize() {
// store the original overflow values
overflow = document.body.style.overflow;
overflowX = document.body.style.overflowX;
overflowY = document.body.style.overflowY;
bodyWidth = document.body.style.width;
bodyHeight = document.body.style.height;
// force the scrollbar
document.body.style.overflow = "scroll";
// activate the scrollbar
document.body.style.width = document.client.width + 1 + "px";
document.body.style.height = document.client.height + 1 + "px";
}
function stopResize() {
// restore the original overflow values; x & y are included because enabling the global overflow will update x and y
document.body.style.overflow = overflow;
document.body.style.overflowX = overflowX;
document.body.style.overflowY = overflowY;
// restore the original body width & height
document.body.style.width = bodyWidth;
document.body.style.height = bodyHeight;
}

How would you use anchor points in a div when using the flexcroll plugin?

I want to have a custom scrollbar on my main div which has buttons to go to certain parts of the div, however anchor points don't seem to work when using the flexcroll plugin (I know i'm doing anchor points correctly because when I disable flexcroll on that div they work fine)
Is their any method I could use to set up the anchor points?
EDIT FOUND SOLUTION: On the buttons I want to click to go to the specific place in the document I can put onclick="Wrapper.fleXcroll.setScrollPos(false,0);"
I've used this function in the past. FYI, I don't know anything about flexcroll, so this is not tested with that:
var isInt = function(val) {
return (parseInt(val, 10) == val);
};
var scrollTo = function(node) {
var pNode = node.parentNode;
var offset = node.offsetTop - pNode.offsetTop;
var pHeight = pNode.clientHeight;
var height = node.clientHeight;
var scrollOffset = pNode.scrollTop;
var buffer = 10;
var scroll = null;
if (scrollOffset > offset) {
scroll = offset - buffer;
} else if (pHeight + scrollOffset < offset + height + buffer) {
scroll = offset + height + buffer - pHeight;
}
if (isInt(scroll)) {
pNode.scrollTop = scroll;
}
};
This is the pure JS version. (example)
Here is an example of a jQuery version, which animates the scroll event: jQuery version

Categories