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()
Related
I'm pretty new to JavaScript. I want to scroll to the very bottom of a website that continually loads more text when you scroll down (like on a Facebook page).
I know the code window.scrollTo(0,document.body.scrollHeight) will scroll to the bottom, causing more of the page to load, but not yet all of it. I was wondering how to execute this until the actual bottom of the page has loaded, or ~100 times.
I tried a for loop, but it didn't scroll more than once. Then I tried a for loop with setTimeout set to 2000 ms (or 2 sec) which also did not work for some reason.
I'm also worried that the page will try to run my code all at once before loading more of the content.
Thanks in advance!
I figured it out, inspired by some other code I found online. I did:
function scrolldown() {
setTimeout(
function()
{
window.scrollTo(0,document.body.scrollHeight);
scrolldown();
}, 2000
)
}
scrolldown()
Still unsure why the delayed for loop did not work though.
The unsuccessful for loop attempt was:
for(var i=0; i<100; i++){
setTimeout(
function(){window.scrollTo(0,document.body.scrollHeight);}, 2000
)
}
You can achieve same using scrollBy function :
function scrolldown() {
setTimeout(
function(){
window.scrollBy(0,50);
scrolldown();
}, 1000)
}
scrolldown()
while window.scrollBy(x,y) used to scroll x & y from Top Left of the page.
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.
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.
I have a problem with a vertical scroll page where I'm using (intending to, that is) two nested quickscroll functions.
This is how it's supposed to look: - just remove the scrollbar in your mind. I'm just using
overflow:scroll
here to manually check on things.
Since JS isn't my forte (I have only very basic knowledge of it), I just got a piece of code that worked similarly, reverse engineered it by removing as much as I could from the HTML and CSS until I was left with the bare function, and plugged it into my own page in terms of the needed HTML and CSS as well as the code. I'm not using anything proprietary and I'm including author links, hoping that I'm on the safe side there (?)
So, the main scroll is a vertical one and inside one of the vertical sections I'm using this 'reverse engineered' horizontal quickscroll code.
The new (nested) script cancels out the main one. Any ideas how to fix this?
The main (vertical scroll) is the following:
<script>
$(document).ready(function() {
$('a.panel').click(function () {
$('a.panel').removeClass('selected');
$(this).addClass('selected');
/* I added this to hide the menu during scroll and I'm mighty proud of myself! :) */
$('.menu').addClass('hide');
$('.book_arrow').addClass('hide');
current = $(this);
$('body').scrollTo($(this).attr('href'), 2600, function(){
$('.menu').removeClass('hide');
$('.book_arrow').removeClass('hide');
});
return false;
});
});
</script>
It comes with these two linked files:
<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script type="text/javascript" src="js/jquery.scrollTo.js"></script>
The conflicting code is a bit longer:
<script>
// initialize scrollable and return the programming API
var api = $("#scroll").scrollable({
items: '#tools'
// use the navigator plugin
}).navigator().data("scrollable");
// this callback does the special handling of our "intro page"
api.onBeforeSeek(function(e, i) {
// when on the first item: hide the intro
if (i) {
$("#intro").fadeOut("slow");
// dirty hack for IE7-. cannot explain
if ($.browser.msie && $.browser.version < 8) {
$("#intro").hide();
}
// otherwise show the intro
} else {
$("#intro").fadeIn(1000);
}
// toggle activity for the intro thumbnail
$("#t0").toggleClass("active", i == 0);
});
// a dedicated click event for the intro thumbnail
$("#t0").click(function() {
// seek to the beginning (the hidden first item)
$("#scroll").scrollable().begin();
});
</script>
...and it links to this file:
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
Does it matter where in the HTML I place all these chunks? In isolation, both scripts are working.
I've read about a seemingly similar case here and I'm thinking that maybe in my case I'm also dealing with variables that are 'occupied' by one of the functions, but I'm not exactly sure what to change and where.
I'm absolutely positively looking forward to learning a major lesson from this problem! :)
Hoping that it doesn't cause the Stack to Overflow, I'll add some more (my solution) to my journey. Maybe it helps posterity to follow my learning curve...
I was able to get the nested quick scroll (as I call it) to work properly. Still a rookie in JS, I played around with that bit of script I had gotten and modified - the one that worked vertically - and stuffed the other, similar, script for the (inner) horizontal scroll into that first script! YAY! It worked. Here's how the final script looks:
<script>
$(document).ready(function() {
$('a.panel').click(function () {
$('.book_arrow').fadeOut();
## which prevents the vertical page flying past a lot of nav during scroll down ##
$('.fluid_centerbox').addClass('hide');
$('.fluid_centerbox').fadeOut();
## which makes the scroll smooth cause what's {display:none;} isn't going to be recalculated
and also lets the viewer appreciate the background images during scroll. the 'hide' is
instant and the .fadeOut is animated. Don't ask me why it worked best in this order! ##
current = $(this);
$('body').scrollTo($(this).attr('href'), 2600, function(){
$('.book_arrow').fadeIn();
$('.fluid_centerbox').fadeIn(), 40000;
});
return false;
});
$('a.panell').click(function () {
current = $(this);
$('.long_wrap').scrollTo($(this).attr('href'), 2600, function(){
});
return false;
});
## the panell is not a typo but a way to distinguish both scroll button types ##
});
</script>
And while I'm posting this, I see that in the inner quick scroll, there's an empty
function(){});
Maybe later I'll try to get rid of it, if possible.
I am currently using jQuery-Smooth-Scroll to smoothly scroll up and down to various anchor positions on one of my pages (Page 1). However, what I would also like to be able to do is, from another page (Page 2), link to Page1 (appending #bookmark to the url) and have jQuery-Smooth-Scroll pick up on the fact I am calling the page with a #bookmark and have it smoothly scroll down to the relevant position once the page has completed loading. I don't know if this is a possibility or not?
This is the version of Smooth-Scroll that I'm using:
https://github.com/kswedberg/jquery-smooth-scroll
I'm still relatively new to jQuery so I may be overlooking something obvious.
Ajma's answer should be sufficient, but for completeness:
alert(location.hash)
Edit: a more complete example:
// on document.ready {
if (location.hash != '') {
var a = $("a[name=" + location.hash.substring(1) + "]");
// note that according to w3c specs, the url hash can also refer to the id
// of an element. if so, the above statement becomes
// var a = $(location.hash);
if (a.length) {
$('html,body').animate({
scrollTop: $(a).offset().top
}, 'slow');
}
}
// }
It's possible, you want to put a call into the smooth scroll function when the page is finished loading. in jQuery, it's using $(document).ready(function () { your code } );
You'll need to put something in to parse your url to extract the #bookmark and then call the smooth scroll.