Automatically scrolling page - javascript

I'm working on an info screen that displays a table of informations which usually is quite long, so I want it to scroll slowly down automatically until it reaches the bottom, fades to white, scroll back up, and fades out from white, repeating the process all over after some delays.
Currently I have this code:
var iInterval = 2000;
var iScrollInterval = 5000;
var iFadeInterval = 500;
var loop = function() {
var iScroll = $(document).height() - $(window).height();
$("html, body").animate({
scrollTop: iScroll
}, {
duration : iScrollInterval,
easing : "linear",
complete : function() {
$("body").fadeOut(iFadeInterval).delay(iFadeInterval);
$("html, body").scrollTop(0);
$("body").fadeIn(iFadeInterval);
}
});
setTimeout(loop, iInterval);
};
setTimeout(loop, iInterval);
The problem with that code is that scrolls down to the bottom, immediately jumps to the top again, without fading and keeps scrolling down immediately without delay.
This behavior is repeating 2-3 times until, finally, the fading to/from white happens, once the bottom of the page is reached for the 3rd time.
There's no doubt I've misunderstood something here, but what?

I haven't been using jQuery for a while, but after looking at your code there is couple of things:
Why are you scrolling both HTML and BODY?
The page jumps back up because you are not animating it here:
$("html, body").scrollTop(0);
And al other problems derive from that. If I have a minute I will update my answer with fiddle
Fiddle:
http://jsfiddle.net/64etqaxc/1/
var iInterval = 2000;
var iScrollInterval = 5000;
var iFadeInterval = 500;
var loop = function() {
var iScroll = $(document).height() - $(window).height();
$("html").animate({
scrollTop: iScroll
}, {
duration : iScrollInterval,
easing : "linear",
complete : function() {
$("body").fadeOut(iFadeInterval, function(){
$("html").scrollTop(0);
$("body").fadeIn(iFadeInterval,function(){
loop();
});
});
}
});
};
loop();

Related

update my offset().top value on window resize

i have 4 offset().top values that i would like updated when i resize the page. i have each value stored as a variable to use with a scrolling animation and css style changes as you scroll down. here is a bit of the code:
var top1 = $('#home').offset().top;
var top2 = $('#profile').offset().top;
var top3 = $('#portfolio').offset().top;
var top4 = $('#contact').offset().top;
$(document).scroll(function () {
var scrollPos = $(document).scrollTop();
if (scrollPos >= top1 && scrollPos < top2) {
$('.nav-bar').css({
'background-color': 'rgba(255, 255, 255, 0.7)',
'color': '#203B40'
});
$("#homeLink").click(function () {
$("html, body").animate({
scrollTop: top1
}, 500);
});
$("#profileLink").click(function () {
$("html, body").animate({
scrollTop: top2 + 8
}, 500);
});
for now, if i manually refresh the page after resize everything matches up fine, on any size. However, if i change the page size without refreshing, the links no longer match up.
i have played around with $(window).resize and window.addEventListener('resize', function) but don't know how to properly use them. i have spent the last three nights scouring google and playing with (breaking) my code. Maybe I just need to reset my variable values on resize, or i have to reset the entire page. i am not sure the best way to deal with this.
here is my codepen with the code. i didnt add the photos or bg imgs. but all the code is there. Thanks for any and all help. https://codepen.io/efe-in-the-mountains/pen/dJLaqK?editors=0010
You need to change your top1,top2,top3,top4 variable when $(window).resize is triggered. Add the snippet below and see if the code is doing what I think you want to do.
$(window).resize(function () {
top1 = $('#home').offset().top;
top2 = $('#profile').offset().top;
top3 = $('#portfolio').offset().top;
top4 = $('#contact').offset().top;
});
Read more here https://developer.mozilla.org/en-US/docs/Web/Events/resize to understand when the resize event is triggered.

Infinite auto scroll top-to-bottom and back, how to control/configure speed, time of pause at end?

I'm trying to make a long page of images scroll up and down infinitely (for an exhibition).
This is what I've been working with (code I found here, so helpful!):
https://jsfiddle.net/p7r73tke/
It's mostly working ok for what I want, but I need more control over speed and pause.
How can I make the pause at the top longer?
is there a way to make it pause randomly for ~1 second ?
does anyone know of an easier way to do what I'm thinking of? maybe as samuel-liew suggests, javascript is not the best solution for the problem
thank u thank u!
function scrollpage() {
function f() {
window.scrollTo(0, i); //idk
if (status == 0) {
i = i + 50; //scroll speed top to bottom?
if (i >= Height) {
status = 30; //idk?
}
} else {
i = i - 10; //scroll speed bottom to top?
if (i <= 1) { // if you don't want continue scroll then remove this if condition
status = 0; //idk
}
}
setTimeout(f, 0.01); //idk
}
f();
}
var Height = 15000; //doc height input manually
var i = 1, //idk
j = Height,
status = 0; //idk
scrollpage();
(I'm new and tender to JavaScript, as you can see in the comments)
Thanks for any help!
jQuery solution:
var speed = 10000; // 10000 = 10 seconds
var doScroll = function() {
var direction = $(window).scrollTop() != 0 ? 0 : $(document).height() - $(window).height();
$('html, body').animate({ scrollTop: direction }, speed, 'linear');
}
doScroll(); // once on page load
setInterval(doScroll, speed + 10); // once every X ms
DEMO: http://jsfiddle.net/samliew/k35tbgau/
JavaScript:
Sorry, I do not recommend pure JavaScript for this as you have to take into account:
Cross-browser issues with getting window height, document height, and current scroll position
Recalculating the scroll speed based on content height every time the browser is resized
Programming an animation function
Keeping track of intervals and timeouts, and when you need to clear them
Direction/state of scroll
Taking into consideration if user manually scrolls the scrollbar
Probably lots more...

Start animation on progress bar when its visible on screen

I want to create a webpage that contains several sections. In one of those sections are something like progress bars. These progress bars are 'animated' so that the user sees them loading on the screen as shown in the example.
Example here
Now this is working as it is but my problem is this:
I want the progress bars to start loading when the bars become visible on the screen.
Once the user scrolls down and gets them in the middle of the screen, the 'animation' should start. The way it is now the animation starts on page load, but the bars are not yet visible as in the following fiddle:
Fiddle
A little extra would be that each bar starts loading after the previous is finished.
I found some similar questions on stack but the answer does not suffice to my needs:
Animate progress bar on scroll & Run animation when element is visible on screen
I tried stuff like (it's not the actual code but it's what I remember of it):
var target = $("#third").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
//start loading progress bar
}
}, 250);
But without any good results.
Can anyone help me on this matter?
Thanks in advance!
Here is a fiddle: http://jsfiddle.net/rAQev/4/
I've used a comparison of scroll offset and your special section offset to detect a moment when this section becomes visible.
Animations are queued to be processed one after another using jQuery queue function, you can read about it in jQuery docs (http://api.jquery.com/queue/).
Also scroll event is unbinded when the first 'loading' happens, not to run 'loading' again and again on scroll event when section is visible.
Here is an updated fiddle http://jsfiddle.net/9ybUv/
This one allows for all the progress bars to run at the same time. If you were like me and had 5 or more it takes a long time to do one, then the next, then the next.
$(function() {
var $section = $('#third');
function loadDaBars() {
$(".meter > span").each(function() {
$(this)
.data("origWidth", $(this).width())
.width(0)
.animate({
width: $(this).data("origWidth")
}, 1200);
});
}
$(document).bind('scroll', function(ev) {
var scrollOffset = $(document).scrollTop();
var containerOffset = $section.offset().top - window.innerHeight;
if (scrollOffset > containerOffset) {
loadDaBars();
// unbind event not to load scrolsl again
$(document).unbind('scroll');
}
});
});
Let me try something
function startProgressBar() {
$(".meter > span").each(function() {
$(this)
.data("origWidth", $(this).width())
.width(0)
.animate({
width: $(this).data("origWidth")
}, 1200);
});
}
$(window).scroll(function() {
var target = $('#third');
var targetPosTop = target.position().top; // Position in page
var targetHeight = target.height(); // target's height
var $target = targetHeight + targetPosTop; // the whole target position
var $windowst = $(window).scrollTop()-($(window).height()/2); // yes divided by 2 to get middle screen view.
if (($windowst >= $targetPosTop) && ($windowst < $target)){
// start progressbar I guess
startProgressBar();
}
});
Give it a try, let me know.

jQuery - stop autoscrolling div when hovered

This is a follow-up post to a previous question: jQuery - scroll down every x seconds, then scroll to the top
I have refined the scrip a little further, but am having a little trouble with the last step.
I have a div that automatically 50px at a time until it reaches the bottom, at which point it scrolls to the top and starts again. I have this working perfectly thanks to the above question and with a little add work.
I need to make all scrolling stop when the div is hovered. I have done part of this already (there is no incremental scrolling down on hover) but I cannot get the full picture. The div will still scroll to the top even when hovered.
Here is my jQuery and a fiddle to go along with it: http://jsfiddle.net/wR5FY/1/
var scrollingUp = 0;
var dontScroll = 0;
window.setInterval(scrollit, 3000);
function scrollit() {
if(scrollingUp == 0 && dontScroll == 0) {
$('#scroller').animate({ scrollTop: $("#scroller").scrollTop() + 50 }, 'slow');
}
}
$('#scroller').bind('scroll', function () {
if (dontScroll == 0) {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
scrollingUp = 1;
$('#scroller').delay(2000).animate({ scrollTop: 0 }, 1000, function() {
scrollingUp = 0;
});
}
}
});
$('#scroller').bind('mouseenter', function() {
dontScroll = 1;
});
$('#scroller').bind('mouseleave', function() {
dontScroll = 0;
});
​
In the fiddle, try hovering the scroller div when the yellow square is visible. You will see that it scrolls to the top.
A couple of notes:
You will notice I have used mouseenter and mouseleave rather than hover and mouseout. This was the best way I could find to ensure all child elements within the div didn't have an adverse affect.
A potential problem area is the fact that I have binded to the scroll event for my function that scrolls to the top. I think this might cause some additional problems when a user is manually scrolling through the items, with my jQuery trying to scroll against the user.
I did a little experimenting with killing setInterval, but I didn't find this to be very helpful as the function that triggers isn't the problem area.
My overall goal here is to lock down all automatic scrolling when a user is hovering or manually scrolling through the list. This is 90% there. If they happen to scroll to the bottom, NOTHING should happen until they move the mouse elsewhere - this is the problem.
Keep it easier ;)
The problem was that you first evaluate wheter dontScroll is zero, then start the timer.
When the timer has ended, it doesnt evaluate anymore, whether dontScroll STILL is zero.
Just pulled that into your scrollIt function:
var scrollingUp = 0;
var dontScroll = 0;
window.setInterval(scrollit, 2000);
function scrollit() {
if(dontScroll == 0){
if ($('#scroller').scrollTop() + $('#scroller').innerHeight() >= $('#scroller')[0].scrollHeight) {
scrollingUp = 1;
$('#scroller').animate({ scrollTop: 0 }, 1000, function() {
scrollingUp = 0;
});
} else if(scrollingUp == 0) {
$('#scroller').animate({ scrollTop: $("#scroller").scrollTop() + 50 }, 'slow');
}
}
}
$('#scroller').bind('mouseenter', function() {
dontScroll = 1;
});
$('#scroller').bind('mouseleave', function() {
dontScroll = 0;
});

reduce number of calls for .resize and .scroll methods

I'm using the following code to find out which part of the page the viewer is visiting (something like google books, to find out the page that's being viewed) :
$("#main-content").scroll(function () {
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(undefined);
});
also in another part I use $(window).resize( ... ) to fit my content in current window size, which is called for every single resize . as you can imagine this slows down the page alot, specially on older hardwares. Is there any way to realise when scrolling or resizing is stopped and then start doing the stuff, so number of processes is reduced ? something like $("#main-content").scrollStop ???
You can do two things.
1.) Set up a timeout so that resize/scroll only happens after some idle state:
var timeout;
$("#main-content").scroll(function () {
clearTimeout(timeout);
timeout = setTimeout(function(){
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(); // note: undefined is passed by default
}, 200);
});
2.) Limit the number of calls / sec:
var lastScroll = 0;
$("#main-content").scroll(function () {
var now = +new Date;
if (now - lastScroll > 100) { // only execute if (elapsed > 100ms)
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select();
lastScroll = now;
}
});
​
Try the function below. It checks if the user has scrolled past a certain no. of pixels, but the function only fires at set intervals (5 times a second in the example below) rather than continuously during scrolling.
var scrollCheck;
$(window).on('scroll', function() {
clearInterval(scrollCheck);
scrollCheck = setInterval(function(){
clearInterval(scrollCheck);
scrollPosition = $(this).scrollTop();
scrollAmount = 150 // no. of pixels that have been scrolled from top
if(scrollPosition > scrollAmount){
alert('scrolled past point')
}else{
alert('not scrolled past point')
}
},200);
});

Categories

Resources