Make overflow automatically go down every few seconds - javascript

I want that scroll would automatically go down a little bit every few seconds and that would expose more text. Is it possible to do that? By overflow I mean this: http://jsfiddle.net/Bnfkv/2/

You can use a timer that relaunches itself it there is anything left to do:
function scroll() {
$('#x').animate({ scrollTop: '+=5px' }, 100, function() {
if($('#x table').height() - this.scrollTop - $('#x').height() > 0)
setTimeout(scroll, 500);
});
}
scroll();
And an updated example: http://jsfiddle.net/ambiguous/2PpyJ/
Note that I added id="x" to your HTML to make it easier to reference the <div>.

var myElement = document.getElementById(.......); // or use jquery
var scrolling = setInterval(
function() {
//pick one:
//myElement.scrollBy(0,1); // if it's a textarea or something
//myElement.scrollTop = myElement.scrollTop+1; // if it's a DIV
},
10 // every 10ms
);
To stop it:
clearInterval(scrolling);

Related

How to add TimeOut to current slider code?

I'm doing an easy slider with buttons, it works fine, but I'd like to add TimeOut() function to current code, to allow slides to change automatically.
I tried to do that with jQuery but it didn't work.
$('.reviews-slider-button').click(function() {
var i = $(this).index();
$('.reviews-slider-person').hide();
$('.reviews-slider-person-' + (i + 1)).show();
});
I'd like to change automatically slider every 10 seconds, and when I would click on .reviews-slider-button it would reset the timer ( to avoid situation I click to change slide, and timer automatically change to the next one).
I'd be grateful for your advice's.
You can use setInterval to click your button every 10 seconds:
var timer = ''; // Make global variable
function ScrollAuto() {
temp = setInterval(function() {
$('.nextButton').click();
}, 10000)
return timer;
}
And to reset your timer, inside your reset button add:
clearInterval(timer);
Similarly to the answer from Shree, but make it cleaner, but use timeout, not interval, you want the system to change slide every 10 seconds unless you click, in which case you reset the timeout, go to the next slide, and set up the next timeout
Something like this:
var slideMaxDuration = 10000; // in ms
var slideTimer = void 0;
function nextSlide() {
clearInterval(slideTimer);
// ... go to next slide ...
}
function autoContinue() {
nextSlide();
setTimeout(autoContinue, slideMaxDuration);
}
$('.reviews-slider-button').click(autoContinue);
You also need to set up the initial autoContinue when you want the whole thing to start.

Pure js add and remove (toggle) class after scrolling x amount?

I don't want to use jQuery for this.
It's really simple, I just want to add a class after scrolling past a certain amount of pixels (lets say 10px) and remove it if we ever go back to the top 10 pixels.
My best attempt was:
var scrollpos = window.pageYOffset;
var header = document.getElementById("header");
function add_class_on_scroll() {
header.classList.add("fade-in");
}
function remove_class_on_scroll() {
header.classList.remove("fade-in");
}
window.addEventListener('scroll', function(){
if(scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
console.log(scrollpos);
});
But console shows a number that continues to grow regardless of scrolling up or down. And the class fade-in never gets added, though console shows we past 10.
You forgot to change the offset value in the scroll handler.
//use window.scrollY
var scrollpos = window.scrollY;
var header = document.getElementById("header");
function add_class_on_scroll() {
header.classList.add("fade-in");
}
function remove_class_on_scroll() {
header.classList.remove("fade-in");
}
window.addEventListener('scroll', function(){
//Here you forgot to update the value
scrollpos = window.scrollY;
if(scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
console.log(scrollpos);
});
Now you code works properly
Explanation
There is no documentation for that, like you asked for. This is just an issue in the logic workflow.
When you say that scrollpos = window.scrollY your page is at an top-offset of 0, so your variable stores that value.
When the page scrolls, your scroll listener will fires. When yout listener checks for the scrollpos value, the value is still 0, of course.
But if, at every scroll handler, you update the scrollpos value, now you can have a dynamic value.
Another option is you to create a getter, like
var scrollpos = function(){return window.scrollY};
This way you can dynamically check what that method will return for you at every offset.
if(scrollpos() > 10)
See? Hope that helped. (:
One simple way to achieve what you want (one line of code inside the scroll event):
window.addEventListener('scroll', function(e) {
document.getElementById('header').classList[e.pageY > 10 ? 'add' : 'remove']('fade-in');
});
#header {
height: 600px;
}
.fade-in {
background-color: orange;
}
<div id='header'></div>
just use the method toggle in classList
header.classList.toggle('fade-in')

Update scroll position on resize of window

I'm currently using a combination of smooth scroll and IDs/anchor tags to scroll to content on my site. The code below is getting the ID of the next 'section' in the DOM, and adding it's ID as the 'view next section' href, so once it's clicked, it'll scroll to the top of that div. Then, it iterates through, updating the href with the next ID each time etc until the last section is seen and it scrolls back to the top. Pretty straightforward.
The only problem is that the 'sections' are fullscreen images, so as it's scrolling to the top of the next section, if you resize the browser, the top position of that section (where we scrolled to) has moved, and means the position is lost.
I've created a JSFiddle. You can see this happening after you click the arrow to visit the next section then resize the window: http://jsfiddle.net/WFQ9t/3/
I'm wanting to keep this top position fixed at all times so even if you resize the browser, the scroll position is updated to reflect this.
Thanks in advance,
R
var firstSectionID = $('body .each-section').eq(1).attr('id');
$('.next-section').attr('href', '#' + firstSectionID);
var i = 1;
$('.next-section').click(function() {
var nextSectionID = $('body .each-section').eq(i).attr('id');
i++;
$('.next-section').attr('href', '#' + nextSectionID);
var numberOfSections = $('body .each-section').length;
var lastSectionID = $('body .each-section').eq(numberOfSections).attr('id');
if ($('.next-section').attr('href') == '#' + lastSectionID ) {
$('.next-section').attr('href', '#introduction');
i = 1;
}
});
Ok, Please check out this fiddle: http://jsfiddle.net/WFQ9t/9/
The few things I did were:
Made some global variables to handle the screen number (which screen you're on and also the initial window height. You will use this when the screen loads and also when you click on the .next-session arrow.
var initWinHeight = $(window).height();
var numSection = 0;
Then I tossed those variables into your resizeContent() function
resizeContent(initWinHeight, numSection)
so that it will work on load and resize
I made the body move around where it needs to, to accomodate for the movement of the divs (I still don't understand what divs are moving when the regular animation happens).
$('body').css({
top: (((windowHeight - initWinHeight)*numSection)*-1) + "px"
});
Then in your click function, I add 1 to the section number, reset the initial window height and then also reset the body to top:0. The normal animation you have already puts the next section at the top of the page.
numSection++;
initWinHeight = $(window).height();
$('body').css({top:"0px"}, 1000);
Finally, I reset the numSections counter when you reach the last page (You might have to make this 0 instead of 1)
numSection = 0;
The fiddle has all of this in the correct places, these are just the steps I took to change the code.
Here is a solution that i found, but I dont use anchor links at this point, i use classes
Here is my HTML code:
<section class="section">
Section 1
</section>
<section class="section">
Section 2
</section>
<section class="section">
Section 3
</section>
<section class="section">
Section 4
</section>
And here is my jQuery/Javascript code,
I actually used a preety simple way:
$('.section').first().addClass('active');
/* handle the mousewheel event together with
DOMMouseScroll to work on cross browser */
$(document).on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('.section.active');
//get the delta to determine the mousewheel scrol UP and DOWN
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
//if the delta value is negative, the user is scrolling down
if (delta < 0) {
next = active.next();
//check if the next section exist and animate the anchoring
if (next.hasClass('section')) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: next.offset().top
}, 800);
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
} else {
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 800);
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
}
});
/*THE SIMPLE SOLUTION*/
$(window).resize(function(){
var active = $('.section.active')
$('body, html').animate({
scrollTop: active.offset().top
}, 10);
});

Waiting until animation is over until replacing data inside the div [duplicate]

This question already has answers here:
How to wait for one jquery animation to finish before the next one begins?
(6 answers)
Closed 1 year ago.
I am having trouble changing the contents of a div. What I want to achieve is wait for the animation to end and then change the content to launch the animation to reveal the new info. This code works from time to time, meaning sometimes it hangs (isWorking never becomes false, because animation freezes or animation never has the time to finish from the constant looping inside the while.) Is there a way to wait for the animation to end and then change the content? (The way you see it below allows me to browse for the new content while the animation is ongoing which saves time for the end user.) Is there a way to catch when the animation ends?
function DesignResults(InnerHTML) {
while(isWorking){
}
$("#holder").html(InnerHTML);
ShowSearch(true);
}
var isWorking = false;
function ShowSearch(show) {
isWorking = true;
var outer = $("#outer");
var inner = $("#inner");
var height = 0;
if (show == true)
height = inner.outerHeight();
var loaderHeight
if (height > 0) {
loaderHeight = 0;
} else {
loaderHeight = 31;
}
outer.animate({
'height': height + "px"
}, 1600, function () {
$("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () { });
isWorking = false;
});
}
I understand that $(elem).is(':animated') will give me if the animation is still in progress, but that still freezes everything due to the constant looping of the while. Can anyone point me to the right direction?
EDIT:
I guess I am misunderstood. Here is the plan I want to achieve:
Start hiding animation.
While the animation is hiding I am launching another function to get the content
If I get the content faster I wish to wait for the animation to end then change the content and show the layer again.
There isn't a issue here if the data takes more than a second to return
I agree that i can do it after the animation completes as you suggested, but I have put the animation to almost 1 second execute time and that time can be used for the data to be pulled from the database. I am looking for the most effective code.
The last parameter in this function:
$("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () { });
Is the 'complete' function. This function is called when the animation is complete.
So, you can do something in this function when it's complete, like so:
$("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () {
alert('animations complete!');
});
----Edit----
Based on your edits, you probably want to do something like this.
Have a variable that will let you know when both are finished:
var signal = 0;
Have a function to change your content with this in it:
function changeContent() {
signal++;
if (signal === 2) {
// change the content code here
signal = 0;
}
}
When the animation is finished, call:
changeContent();
When you've grabbed the data, call:
changeContent();
When changeContent() is called the first time by either function, it will increment signal to 1 and exit the function. Then on the second time, it will increment signal to 2. Since signal === 2, you know that both the animation and grabbing the data is complete, so you can now change your content.
The good part about using an integer to do this, is if you want to have 3, 4, 5+ functions finish working before changing your content. In this case you just have to change the condition by increasing the number in if (signal === 2).
Just add the additional task here
$("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () { /* Change Content */ });
Than it would be execute after the animation

Difficulty with setInterval loop using class of Divs

$(document).ready(function fadeIt() {
$("#cool_content > div").hide();
var sizeLoop = $("#cool_content > div").length;
var startLoop = 0;
$("#cool_content > div").first().eq(startLoop).fadeIn(500);
setInterval(function () {
$("#cool_content > div").eq(startLoop).fadeOut(1000);
if (startLoop == sizeLoop) {
startLoop = 0
} else {
startLoop++;
}
$("#cool_content > div").eq(startLoop).fadeIn(1500);
}, 2000);
});
Here I want a class of divs to animate, infinitely!
However, because the interval is set to two seconds there is period where no div is showing!
What would be an appropriate way to loop the animation of these divs?
I thought about using a for loop but couldn't figure out how to pass a class of divs as arguments. All your help is appreciated.
Thanks!
Ok, generally, you should know that Javascript is a single threaded environment. Along with this, the timer events are generally not on time accurately. I'm not sure how jQuery is doing fadeIn and fadeOut, but if it's not using CSS3 transitions, it's going to be using timeOut and Intervals. So basically, there's a lot of timer's going on.
If you go with the for loop on this one, you'd be blocking the single thread, so that's not the way to go forward. You'd have to do the fade in/out by yourself in the setInterval.
Setting the opacity on each interval call. Like div.css('opacity', (opacity -= 10) + '%')
If you're trying to fade in and out sequentially, I think maybe this code would help
var opacity = 100,
isFadingIn = false;
window.setInterval(function() {
if (isFadingIn) {
opacity += 10;
if (opacity === 100) isFadingIn = false;
} else {
opacity -= 10;
if (opacity === 0) isFadingIn = true;
}
$('#coolContent > div').css('opacity', opacity + '%');
}, 2000);
Consider the following JavaScript / jQuery:
$(function(){
var divs = $('#cool_content > div').hide();
var curDiv;
var counter = 0;
var doUpdate = function(){
// Hide any old div
if (curDiv)
curDiv.fadeOut(1000);
// Show the new div
curDiv = divs.eq(counter);
curDiv.fadeIn(1000);
// Increment the counter
counter = ++counter % divs.length;
};
doUpdate();
setInterval(doUpdate, 2000);
});
This loops infinitely through the divs. It's also more efficient than your code because it only queries the DOM for the list of divs once.
Update: Forked fiddle
instead of
if (startLoop == sizeLoop)
{
startLoop = 0
}
else
{
startLoop++;
}
use
startLoop =(startLoop+1)%sizeLoop;
Check the demo http://jsfiddle.net/JvdU9/ - 1st div is being animated just immediately after 4th disappears.
UPD:
Not sure I've undestood your question, but I'll try to answer :)
It doesn't matter how many divs you are being looped - 4, 5 or 10, since number of frames are being calculated automatically
x=(x+1)%n means that x will never be greater than n-1: x>=0 and x<n.
x=(x+1)%n is just shorten equivalent for
if(x<n-1)
x++;
else
x=0;
as for me first variant is much readable:)
And sorry, I gave you last time wrong demo. Correct one - http://jsfiddle.net/JvdU9/2/

Categories