JavaScript - Scroll to bottom of Div - Keeps on scrolling down without stop - javascript

So I have this function which scrolls down to the bottom of the page, and to the bottom of the scrollable div #log:
function gotoConsole() {
var console = document.getElementById('log');
window.scrollTo(0,document.body.scrollHeight);
window.setInterval(function() {
console.scrollTop = console.scrollHeight;
}, 250);
}
It does the job, it scrolls down to the page and scrolls to the bottom of the div. But the problem is; The div keeps on going down, I cannot scroll up.
The gotoConsole() function is called only once after the user clicks on a button.
What is the problem with this function? I cannot use jQuery for this.

I think that you may be misunderstanding setInterval. setInterval() will repeat infinitely unless you specifically clear it using clearInterval.
I believe what you're after is setTimeout - it functions very similarly to setInterval, though rather than repeating, it only runs once.
function gotoConsole() {
var myConsole = document.getElementById('log');
window.scrollTo(0,document.body.scrollHeight);
window.setTimeout(function() {
myConsole.scrollTop = myConsole.scrollHeight;
}, 250);
}
Side note:
Setting a variable to console is a major red flag.
When writing/debugging JavaScript, your best friend is very often going to be
console.log(). When you set a variable to the same name, you lose the ability to reference console within that scope without doing window.console.log() which is a cumbersome annoyance.

Related

Auto-Scroll Fast in JS

I have a HTML which is very long. I would like to auto-scroll the content on load. My requirements are:
Go to top when page opened.
Scroll to the utmost bottom.
Here's what I tried:
function pageScroll() {
window.scrollBy(0,7000);
scrolldelay = setTimeout('pageScroll()',1000);
}
This works well but I want it to be faster and also I would like a replacement of 7000.
These are the values which should work best in my opinion
function pageScroll() {
window.scrollBy(0, 3060) //don't set a timeout function
}
pageScroll()

getBoundingClientRect during throttled scroll event handling

I faced an issue during my project developing, it's related to a difference between getBoundingClientRect values with and without preventive break points during debugging. Trying to minimize repro, I got following.
const scrollHandler = () => {
setTimeout(() => {
const top = document.getElementById('test').getBoundingClientRect().top;
console.log(top);
});
};
document.getElementById('viewport').addEventListener('scroll', scrollHandler);
where the viewport is just scrollable div with fixed height. The content of the viewport is big enough to be able to fire at least one scroll event. I also created Plunker demo. All magic happens inside of setTimeout callback.
Now the steps. Success scenario.
Set break point at the beginning of the setTimeout callback.
Fire scroll event.
Make "step over" to obtain top value.
Execute document.getElementById('test').getBoundingClientRect().top in the console.
The results of 3 and 4 are the same.
Failed scenario.
Set break point at the end of the setTimeout callback.
Fire scroll event.
Get the value of top variable (no action is needed).
Execute document.getElementById('test').getBoundingClientRect().top in the console.
The results of 3 and 4 are not the same.
To avoid any misunderstanding with this repro, I recorded a short demo movie with the above steps.
In my project I'm doing calculations in a similar environment (throttled scroll events) and getting wrong results that don't match expectations. But when I debug it, I'm getting different picture; a preventive break point fixes calculations.
Is it a bug or known issue? Or did I miss something? should I refuse to use getBoundingClientRect in such a situation?
I'm not sure what it is that you are looking for but assume your animation on scroll isn't working as expected.
There is a tip on throttling scroll here that is incorrect. Let's say you throttle to every 30 milliseconds. If page stops scrolling 25 milliseconds after last animation then you're stuck with a scroll position 25 milliseconds before it stopped scrolling.
Maybe a better way to do it is this (can test in the console on this page):
var ol = document.querySelectorAll("ol")[2];
window.onscroll = ((lastExecuted)=>{
const expensiveHandler = e => {
lastExecuted=Date.now();
//do some animation maybe with requestAnimationFrame
// it may prevent overloading but could make animation
// glitchy if system is busy
console.log("1:",ol.getBoundingClientRect().top);
};
var timerID
return e=>{
if(Date.now()-lastExecuted>19){
//only animate once every 20 milliseconds
clearTimeout(timerID);
expensiveHandler(e);
}else{
//make sure the last scroll event does the right animation
// delay of 20 milliseconds
console.log("nope")
clearTimeout(timerID);//only the last is needed
timerID=setTimeout(e=>expensiveHandler(e),20);
}
}
})(Date.now())

Scrolling to the bottom of a page that changes height

I want to scroll to the bottom of a webpage using JS and, looking online, most people say to use
window.scrollTo(0,document.body.scrollHeight);
However the page I want to scroll down changes its height as you reach the bottom (it continuously loads more and more of the page) so its height is not fixed. The eventual height also varies (thus I cannot just scroll to the final height of the page) so I need some way of scrolling until it determines it has reached the bottom (it cannot scroll any further).
If you have infinite scroll, you actually need to incorporate that in your design. E.g. scrollToBottom should look like this:
function scrollToBottom(lastOffset) {
const offset = document.body.scrollHeight;
// check if no more scrolling required.
if (lastOffset === offset) {
return;
}
// if it is, go to bottom.
window.scrollTo(0, offset);
// Now, trigger your `loadMore` logic, whatever it might be, then call scrollToBottom again.
triggerLoadMore().then(() => scrollToBottom(offset));
// or triggerLoadMore(() => scrollToBottom(offset));
}
// call this somewhere after your initial load.
Now, triggerLoadMore, erm, triggers your loadMore logic. I included two versions in the above code, one being promise-based, the commented one being callback-based. It should call back your function (scrollToBottom) when it has loaded more and put it on the screen. How you do that, depends on what you use, and is possibly another question.
Now, there's a third option here, that your trigger is something that you cannot call directly, because it's tied to window.scroll event or some such logic. In that case, you need to write this bit of logic at the end of such function flow - load more, render on screen, scroll. Which then triggers the cycle again.
#Zlatko answer is the best performance. However, you can use this one in every context :
window.addEventListener( 'resize', function(){
window.scrollTo(0,document.body.scrollHeight);
});
Sounds like you need to reach bottom of the page, wait for load and scroll to bottom again. You can't reach the end of the page where you cannot know the end.
function scroll_and_wait(){
return new Promise(
function(resolve, reject){
setTimeout(function(){
resolve(window.scrollTo(0,document.body.scrollHeight));
}, 500);})}
async function scroller(n){while(n>0){await scroll_and_wait();n=n-1;}}
scroller(5)
Calling scroller function will scroll to to bottom of the page as many times as you specify with 500ms pause for loading.

SetInterval loop relatively confusing to me

HTML
<div id="backspace" ng-click="deleteString(''); decrementCursor();">
JS
<script>
$scope.deleteString = function() {
if($scope.cursorPosVal > 0){
//$scope.name = $scope.name - letter;
$scope.name = [$scope.name.slice(0, $scope.cursorPosVal - 1) + $scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
} else {
$scope.cursorPosVal = 1;
}
};
</script>
I am designing an on screen touchscreen keyboard. This is my backspace button. I am going to make it so that when you click and hold the backspace button, it starts removing characters automatically. I don't know where to begin with creating a setInterval, and I know a setInterval is exactly what I need to use here.
If I'm not wrong, you want that while you're keeping your button pressed, a function repeats itself.
You're right with setInterval(). However, the way you manage the event is wrong.
Take a look at this fiddle (It's not your code, but a simple example is the best way to understand):
http://jsfiddle.net/daq9atdd/1/
$(function(){
var interval = null;
$('#myButton').mousedown(function(){
interval = setInterval(function(){
console.log('Hello !');
}, 250);
});
$('#myButton').mouseup(function(){
clearInterval(interval);
});
});
I start the interval when the button is pressed, store it, and clear it when the button is released.
You’re so sure about setInterval.
If browser briefly hangs for whatever reason (say some background task), setInterval would go on queueing your backspace calls until it has some CPU time. This means user may see no change and hold backspace longer than needed, and then see a whole bunch of characters suddenly vanish when browser is back to normal.
Thus by setting a timeout after every call you’re making sure user won’t remove more characters than needed. Might be important if the goal is to improve UX.
Example implementation with AngularJS directives and setTimeout
See also:
setTimeout or setInterval?
noKid’s fiddle updated with setTimeout in mind

How can I reveal content and maintain its visibility when mousing to a child element?

I'm asking a question very similar to this one—dare I say identical?
An example is currently in the bottom navigation on this page.
I'm looking to display the name and link of the next and previous page when a user hovers over their respective icons. I'm pretty sure my solution will entail binding or timers, neither of which I'm seeming to understand very well at the moment.
Currently, I have:
$(document).ready(function() {
var dropdown = $('span.hide_me');
var navigator = $('a.paginate_link');
dropdown.hide();
$(navigator).hover(function(){
$(this).siblings(dropdown).fadeIn();
}, function(){
setTimeout(function(){
dropdown.fadeOut();
}, 3000);
});
});
with its respective HTML (some ExpressionEngine code included—apologies):
<p class="older_entry">Older<span class="hide_me">Older entry:
<br />
{title}</span></p>
{/exp:weblog:next_entry}
<p class="blog_home">Blog Main<span class="hide_me">Back to the blog</span></p>
{exp:weblog:prev_entry weblog="blog"}
<p class="newer_entry">Newer<span class="hide_me">Newer entry:
<br />
{title}</span></p>
This is behaving pretty strangely at the moment. Sometimes it waits three seconds, sometimes it waits one second, sometimes it doesn't fade out altogether.
Essentially, I'm looking to fade in 'span.hide_me' on hover of the icons ('a.paginate_link'), and I'd like it to remain visible when users mouse over the span.
Think anyone could help walk me through this process and understand exactly how the timers and clearing of the timers is working?
Thanks so much, Stack Overflow. You guys have been incredible as I walk down this road of learning to make the internet.
If you just want to get it working, you can try to use a tooltip plugin like this one.
If you want to understand how this should be done: first, get rid of the timeout, and make it work without it. The difference (from the user's point of view) is very small, and it simplifies stuff (developing and debugging). After you get it working like you want, put the timeout back in.
Now, the problem is you don't really want to hide the shown element on the navigator mouse-out event. You want to hide it in its own mouse out event. So I think you can just pass the first argument to the navigator hover function, and add another hover to dropdowns, that will have an empty function as a first argument, and the hiding code in its second argument.
EDIT (according to your response to stefpet's answer)
I understand that you DO want the dropdown to disappear if the mouse moves out of the navigator, UNLESS its moved to the dropdown itself. This complicates a little, but here is how it can be done: on both types of items mouse-out event, you set a timer that calls a function that hides the dropdown. lets say the timer is 1 second. on both kind of item mouse-in even, you clear this timer (see the w3school page on timing for syntax, etc). plus, in the navigator's mouse-in you have to show the dropdown.
Another issue with the timer in your code is that it will always execute when mouse-out. Due to the 3 seconds delay you might very well trigger it again when mouse-over but since the timer still exist it will fade out despite you actually have the mouse over the element.
Moving the mouse back and forth quickly will trigger multiple timers.
Try to get it to work without the timer first, then (if really needed) add the additional complexity with the delay (which you must keep track of and remove/reset depending on state).
Here was the final working code, for anyone who comes across this again. Feel free to let me know if I could have improved it in any ways:
$(document).ready(function() {
var dropdown = $('span.hide_me');
var navigator = $('a.paginate_link');
dropdown.hide();
$(navigator).hover(function(){
clearTimeout(emptyTimer);
$(this).siblings(dropdown).fadeIn();
}, function(){
emptyTimer = setTimeout(function(){
dropdown.fadeOut();
}, 500);
});
$(dropdown).hover(function(){
clearTimeout(emptyTimer);
}, function(){
emptyTimer = setTimeout(function(){
dropdown.fadeOut();
}, 500);
});
});

Categories