Div Overflow Scroll-to-bottom: Is it possible? - javascript

If I have a div with overflow:auto so that it is a scrollable div and I load it with information that makes a significant scroll area, is there a way that when I load the information, the div shows the bottom results? Or essentially scrolls to the bottom?
I've seen jQuery solutions but this is for use in an HTA so I cannot use jQuery. Is there a purely javascript way to accomplish this?

var myDiv = document.getElementById('myDiv');
myDiv.scrollTop = myDiv.scrollHeight;
Works in Firefox, Safari, Opera, Chrome and even Internet Explorer, which is more than I can say for the SSE test case I Set up... lol
I will spare you the rant about the obtuse solutions offered by others, and here is an example of code that could be used for an instant messaging type client.
document.body.onload = function()
{
var myDiv = document.getElementById('myDiv');
// Pick your poison below, server sent events, websockets, AJAX, etc.
var messageSource = new EventSource('somepage');
messageSource.onmessage = function(event)
{
// You must add border widths, padding and margins to the right.
var isScrolled = myDiv.scrollTop == myDiv.scrollHeight - myDiv.offsetHeight;
myDiv.innerHTML += event.data;
if(isScrolled)
myDiv.scrollTop = myDiv.scrollHeight;
};
};
The part of that example that is relevant checks to see if the div is already scrolled to the bottom, and if it is, scrolls it to the bottom after adding data to it. If it is not already scrolled to the bottom, the div's scroll position will stay such that the visible content of the div is unaffected by adding the data.

document.getElementById('mydiv').scrollTop = 9999999;
The scrollTop property specifies the scrolling offset in pixels from the top of the region. Setting it to a very large value will force it to the bottom.

How about this?
function scroll_to_max(elm) { // {{{
if(!scroll_to_max_el) {
scroll_to_max_el = elm;
setTimeout(scroll_to_max, 10); // Allow for the element to be updated
} else {
var el = scroll_to_max_el;
var t = el.scrollTop;
el.scrollTop = t+100;
if(el.scrollTop != t) {
setTimeout(scroll_to_max, 10); // Keep scrolling till we hit max value
} else {
scroll_to_max_el = null;
}
}
}
var scroll_to_max_el = null; // Global var!
// }}}
(NOTE: Only tested it in Chrome...)

Late answer but this is much more helpful
$('#mydiv').scrollTop(($('#mydiv').height()*2));

I think you need to set the scrollTop after the element is updated.
setTimeout(function (){
el.scrollTop = 999999999
}, 10)
also, in chrome at least, 99999999999 will scroll to the bottom. but 999999999999 (an extra 9) will scroll to the top. it's probably converted to an int in the C side of webkit.

Related

add dom before current dom, and keep current dom stay in the viewport

Assume there is a scroll list, when I insert some new DOM append to the current dom, it works fine.
pullup
But if I insert some new DOM before, the new DOM will be in the viewport, and the old DOM will be push down.
pulldown
Is there a way that I can make pulldown behave like pullup? Without manually set scrollTop after?
In Google Chrome, I cannot reproduce the behavior you describe. Could there be a difference in how browsers manage maintaining scroll positions upon DOM edits?
In Safari, I do see the behavior you describe. I'm not aware of any different injection methods to bypass the issue, and I don't think css-like tricks such as translateY or position: absolute are the way to go...
So, that brings us to the one option you said you didn't want to use... Modifying scrollTop. I don't see many problems with an approach like this though...
function scrollSafeInsertBefore(fragment, el, scrollContainer) {
var scroller = scrollContainer || document.body;
var parent = el.parentElement;
var aboveScroll = el.getBoundingClientRect().top < 0;
if (aboveScroll) {
var st = parent.scrollHeight;
parent.insertBefore(fragment, el);
var dy = parent.scrollHeight - st;
scroller.scrollTop += dy; // Move back the height change
} else {
parent.insertBefore(fragment, el); // Normal injection
}
}
Fiddle: https://jsfiddle.net/pq4t2zbn/ (press the insert button)

detecting how much of a div is beyond window height

I have a fixed div that I want to sit on top of a number of background images. The issue is that if this fixed div is taller than the window, it wont scroll, meaning content is lost. I've tried using max-height: 100% and y-overflow:scroll; but no luck.
I have figured a workaround using the following javascript:
<script>
$(window).scroll(function(){
var css = {};
if ($(window).scrollTop() > 120){
css = { top:'0'};
}
else {
css = {top:'120'};
}
$('#writtenContent').animate(css,{duration:200,queue:false});
});
</script>
Which moves it up, but this is not ideal for a number of reasons. Id like to either be able to know how much of the div is hidden, and then move up that amount, or have the fixed div scrollable. Ideally either of these should only happen if necessary i.e. if the div fits in the window, then no action taken.
Any ideas would be great!
===============UPDATE=================
Hi guys - here is a quick jsfiddle showing the type of thing. Its a stripped down version, but shows the problem Im having. If the window is resized to be smaller than the content holding div, we loose it.
Ok well first off, you said that it's a fixed div, which generally means position:fixed but then you say position:relative? What do those refer to? But it really should be scrolling. You said you tried y-overflow but of course that won't work. It's overflow-y with the y after. Try that again and see if it works. If it doesn't work then you will need to post all of the relevant code and styles so we can see what is going on.
Also it's somewhat hackish but try using max-height: with varying percentages less than 100% to see if it works even a little bit correctly.
If I'm understanding you correctly, this will work for you.
var win = window,
$writtenContent = $('#writtenContent'),
$writtenContentPosition;
function windowScrollMagic(){
$writtenContentPosition = $writtenContent.offset().top; // get elements distance from top
// if you've scrolled farther than the elements position:
if (win.scrollY > $writtenContentPosition) {
// do something, like animating $writtenContent to the win.scrollY coordinate
}
}
$(document).ready(function(){
$(win).scroll(){
windowScrollMagic();
});
});
Update in response to example jsfiddle:
var $win = $(window),
$winHeight,
$writtenContent = $('#writtenContent'),
$writtenContentPosition,
$writtenContentHeight,
$writtenContentBottomEdgePosition,
heightDifference;
function calculateHeights() {
$winHeight = $win.height();
$writtenContentPosition = $writtenContent.offset().top;
$writtenContentHeight = $writtenContent.height();
$writtenContentBottomEdgePosition = $writtenContentPosition + $writtenContentHeight;
heightDifference = $winHeight - $writtenContentBottomEdgePosition;
}
function windowResizeMagic() {
calculateHeights();
if (heightDifference < 0) {
$('#alert').html('Written Content is off screen by ' + heightDifference + 'px');
} else {
$('#alert').html('Written Content is not off screen');
}
}
$(document).ready(function(){
calculateHeights();
$win.resize(function(){
windowResizeMagic();
});
});

Is there any way to control scroll bar using JavaScript?

In my below code a function to scroll DIV for every set of intervals where when I try to scroll up due to interval refresh scroll bar again coming down.
My code:
var int = self.setInterval("f2()", 1000);
function f2() {
var objDiv = document.getElementById("messages2");
objDiv.scrollTop = objDiv.scrollHeight;
}
Now, by using onscroll property for DIV is there anyway to stop scrolling down when holding scroll bar with mouse?
Something like
var int = self.setInterval("f2()", 1000);
function f2() {
var objDiv = document.getElementById("messages2");
// if(objDiv.onscroll) i.e. when the particular DIV's scroll bar is on hold by cursor.
{
return false;
}
else
{
objDiv.scrollTop = objDiv.scrollHeight;
}
}
If the above kind of function can be implemented anybody please correct its syntax. I am a newbie to JavaScript.
Thanks in advance..!
I’m not sure what you are asking here, but window has a scroll event that you can listen to, and so does any other element that has overflow: auto|scroll set using CSS.
You can’t prevent the default scrolling behavior, but you can use the scrollTo() method or the scrollTop property if you want to do something annoying like:
window.onscroll = function() {
window.scrollTo(0,0);
};
Here is a nice compat table of the scroll event: http://www.quirksmode.org/dom/events/scroll.html
scrollTo() docs: https://developer.mozilla.org/en/Window.scrollTo

Adjusting window scroll position in JavaScript to counteract element's resizing above

I'm trying to counteract an adjustment to the height of an element which is above the scroll offset by calculating the difference in height and then updating the current scroll position to account for it.
The problem is that there's no way that I can prevent a very quick flickering artefact. Whether I adjust the element's height and then the scroll position, or vice versa, I can't seem to prevent a quick visual jump.
Does anyone know how this could be overcome? I want these to operations to happen at the same time with no rendering in-between but I'm not sure if it's possible.
// Setup
...
var myElement = ...
var oldHeight = ...
var scrollOffset = window.scrollY;
var newHeight = 100;
var diff = newHeight - oldHeight;
// Determine if we need to counteract new size
var adjustScroll = (absoluteOffset(myElement) < scrollOffset);
// Adjust size
myElement.style.height = newHeight+'px';
// Adjust scroll to counteract the new height
if (adjustScroll) window.scrollTo(0, scrollOffset+diff);
I'm working with WebKit, specifically on iOS.
for webkit you can use CSS transitions/animations to smooth this but it's still sound like you are going the wrong way to begin with. I am sure that whatever is it you are trying to do can be solved purely with CSS (maybe with some very minimal Javaqscript). Post an example of you HTML + CSS + JS.
You could use scrollIntoView with timers to simulate multiple threads.
Or you could do it inside a document fragment beforehand.
Sorry to be reviving an old post here, but i came across this looking for a solution to a similar problem to do with browser resizing.
Stackoverflow user James Kyle created this little jsfiddle using jQuery that attempts to maintain scroll position as best as possible when a page is resized
var html = $('html'),
H = html.outerHeight(true),
S = $(window).scrollTop(),
P = S/H;
$(window).scroll(function() {
S = $(window).scrollTop();
P = S/H;
});
$(window).resize(function() {
H = html.outerHeight(true);
$(window).scrollTop(P*H);
});
http://jsfiddle.net/JamesKyle/RmNap/
you could try using this same code and trigger a 'resize' event on the html when the image has loaded by using a jQuery library like imagesLoaded

issue with $(document).scrollLeft() as a variable

I'm trying to use the left variable to replace '1493' in this code. It works fine when it's a number but when I changed it over to use 'left' the if statement stops working.
$(document).scroll(function () {
var width = $(document).width();
var left = $(document).scrollLeft();
var postCount = $(".post").length;
var columnLength = ( width - ((postCount*743) - 1493)) - (width-(postCount*743));
if(left >= columnLength) {
$(".num").text(left);
}
});
Does anyone have any ideas where I'm going wrong with this? Any pointers would be great.
You may need to force it to be an integer:
var left = parseInt($(document).scrollLeft());
Lets take a look at the math you have really quick.
var columnLength = ( width - ((postCount*743) - 1493)) - (width-(postCount*743));
You are basically cancelling out width, and (postCount*743). It leaves you with --1493 which is positive 1493. The following would have the same effect:
var columnLength = 1493;
So, the reason the if statement fires when you put in the static value 1493, is because columnLength ALWAYS equals 1493 which, of course satisfies this condition:
if (1493 >= columnLength)
You could as easily write:
if (1493 >= 1493)
That said, it should still, theoretically fire when left becomes greater than or equal to 1493. But left is the current horizontal scroll position in pixels. It would be a HUGELY wide page to hit a scroll position of 1493.
Edit: Here's a fiddle to give an idea of how fast the scroll position increases: http://jsfiddle.net/vdQ7B/16/
EDIT 2:
Here is an update in response to your comment.
As I understand it, you were trying to get a horizontal scrollbar that would, essentially, scroll forever.
Please see the following fiddle for a demo: http://jsfiddle.net/vdQ7B/40/
The code is below:
$(document).scroll(function () {
var width = $(document).width();
var left = $(document).scrollLeft();
var viewportwidth = window.innerWidth;
// If our scrollbar gets to the end,
// add 50 more pixels. This could be set
// to anything.
if((left + viewportwidth) === width) {
$("body").css("width", width + 50);
}
});
Per the comments in the code, we simply increase the width of the body if we determine we've reached the end. scrollLeft() will only tell us the number of pixels that are currently not visible to the left of the viewable area. So, we need to know how much viewable area we have, and how much is hidden to the left to know if we've scrolled all the way to the end.
If you have a scroll bar on an inner element, like a div, you'd need to update with width of the div, not the body.
Note: You may also need to use $(window) instead of $(document) to get scrollLeft() to work across all browsers.
Note: See here about using "innerWidth". There are some compatibility issues, and you may need to expand it a bit to handle other cases (IE6).

Categories

Resources