I want to animate 0 counting up to 100 - javascript

I have made a 10 slide presentation and I'm pretty happy with it but it looks a little stale, I want to add some animations and nice effects in there.
I currently have some text that reads '100%' i would like the page upon load to be at zero and then quickly count up to 100.
How would I do this?

$(document).ready(function(){
var count = 0;
var counting = setInterval(function(){
if(count < 101) {
$('.text').text(count + '%');
count++
} else {
clearInterval(counting)
}
}, 10);
});

Related

JS < (less than) Operator Failing

I have a script that AJAXes a request every 10 seconds (but technically 11), for the user. I have a simple countdown made from 10 to 0 and then again and again.
This countit function is called after each AJAX request to restart
Here is my code:
function countit() {
var count = 10;
loading = setInterval(function() {
$(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
count--;
if (count <= 0) {
clearInterval(loading);
}
}, 1000);
}
The code works fine except, if you leave the page and come back, the countdown proceeds into negative and does not stop. Here is the image:
I cant be sure if this is a problem with the code or JS but the counter doesnt go below 0 when the user stays on the page.
As Ibrahim & Chris have said:
Add a var infront of the Interval as without it, the variable is global.
function countit() {
var count = 10;
var loading = setInterval(function() {
$(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
count--;
if (count <= 0) {
clearInterval(loading);
}
}, 1000);
}

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...

Simple loop for images

I'm trying to build a simple image slider (but using a fade effect). Every two seconds, the image should change to another image. At the end, it should call repeat_sponsor() again, to start over, so it becomes a loop.
I've written this (highly ineffective) code for 5 images. Turns out I'm going to need it for around 50 images. My editor just freezes when I add too much code.
I've tried using while-loops, but I just can't figure it out how to do this the right way.
Anyone who can help me with this?
function repeat_sponsor()
{
$("#sponsor2").hide();
$("#sponsor3").hide();
$("#sponsor4").hide();
$("#sponsor5").fadeOut("slow");
$("#sponsor1").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor2").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor3").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor4").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor5").fadeIn("slow", ...
(function (){
var cnt = 50; //set to the last one...
var max=50;
function show() {
$("#sponsor" + cnt).fadeOut("slow"); //if you want the fadeout to be done before showing next, put the following code in the complete callback
cnt++;
if(cnt>max) {
cnt=1;
}
$("#sponsor" + cnt).fadeIn("slow");
window.setTimeout(show, 2000);
}
show();
})();
But the real issue is the fact you are loading tons of images from the start. You will be better off changing it so you only have a small subset of images and change the source.
You should use some sort of for loop and a class for hiding the images. and add a max value that if checks out resets c & i
var i=0;
var c=1;
function repeat_sponsor()
{
$("#sponsor"+i).fadeOut("slow");
$(".sponsers").hide()
$("#sponsor"+c).fadeIn("slow", function() {
window.setTimeout(repeat_sponsor(), 3000);
}
i++;
c++;
}
Just run a function every two seconds with setInterval and appropriately target your different sponsor divs:
var i = 1;
var max = 50;
setInterval(function() {
// Could target all other sponsor images with a class "sponsor"
$('.sponsor').fadeOut();
// Execute code on the target
$("#sponsor" + i).fadeIn();
if (i === max) {
i = 0;
}
i++;
}, 2000);

show and hide with delays on a loop but no animation

I have a jsfiddle for this
Jsfiddle
The problem is, I am trying to create a script that ones a button is clicked flashes an image (car lights) on and off for a period of time. It works fine, but in IE8 since the lights are png the animation for it is causing a black background and border as it blinks on and off. So I trying to duplicate the same thing, but without using animation.
In my jsfiddle, the first function for the first click div represents what i am trying to do without animation, but it is not repeating. The code:
$('.oneD').click(function(){
for (var i = 0; i <= 9; i++) {
$('.oneP').show();
setTimeout(function(){
$('.oneP').hide();
}, 1000);
}
});
The 2nd function is the one I already created that does work, but it has the animation:
$('.twoD').click(function(){
for (var i = 0; i <= 9; i++) {
$(".twoP").fadeIn(1000, function () {
$(".twoP").hide();
});
}
});
Keep in mind that the jsfiddle is just a simple mock not using images. I am just looking for the functionality in which i can incorporate this. I appreciate your time in helping me with this.
instead of setTimeout() use setInterval() and clearInterval() like this:
$('.oneD').click(function(){
$('.oneP').show();
var interval = setInterval(function(){
$('.oneP').hide();
}, 1000);
//*after a number of time or loop
interval.clearInterval();
});
setInterval() "Loop" throught the function it is given every number of millisecond you pass it. and clearInterval() stop the "Loop".
I'd do it like this :
$('.oneD, .twoD').on('click', function(){
for (var i=0; i<9; i++)
$('.'+this.className.replace('D', 'P')).delay(1000).show(0)
.delay(1000).hide(0);
});
FIDDLE
This uses a selector for both elements and the same event handler, then swaps out the D for a P in the showing and hiding.
As for using delay() and making this work, hide() and show() will work just as the animated jQuery methods if a value for the duration is passed, even if that value is zero.
Fiddle here: http://jsfiddle.net/HxFpr/
var i;
$('.twoD').click(function(){
i = 0;
loopFlash();
});
function loopFlash(){
if(i < 10){ // flash 5 times (1 on 1 off = 2 cycles)
$('.twoP').toggle();
var flashing = setTimeout(loopFlash,500);
}
i++;
}
Yet another solution for you.
No Animation - with single interval
With animation - pure jQuery
http://jsfiddle.net/x6Kpv/6/
var noAnimationHandler = function() {
setInterval(function() {
var $el = $('.oneP');
$el[$el.is(":visible") ? "hide" : "show"]();
}, 800);
};
var animationHanddler = function() {
$('.twoP').fadeIn(300, function() {
$(this).delay(150).fadeOut(300, animationHanddler);
});
}
$('.oneD').click(noAnimationHandler);
$('.twoD').click(animationHanddler);
Thanks

smooth auto scroll by using javascript

I am trying to implement some code on my web page to auto-scroll after loading the page. I used a Javascript function to perform auto-scrolling, and I called my function when the page loads, but the page is still not scrolling smoothly! Is there any way to auto scroll my page smoothly?
Here is my Javascript function:
function pageScroll() {
window.scrollBy(0,50); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroll()',100); // scrolls every 100 milliseconds
}
It's not smooth because you've got the scroll incrementing by 50 every 100 milliseconds.
change this and the amount you are scrolling by to a smaller number to have the function run with the illusion of being much more 'smooth'.
turn down the speed amount to make this faster or slower.
function pageScroll() {
window.scrollBy(0,1);
scrolldelay = setTimeout(pageScroll,10);
}
will appear to be much smoother, try it ;)
Try to use jQuery, and this code:
$(document).ready(function(){
$('body,html').animate({scrollTop: 156}, 800);
});
156 - position scroll to (px), from top of page.
800 - scroll duration (ms)
You might want to look at the source code for the jQuery ScrollTo plug-in, which scrolls smoothly. Or maybe even just use the plug-in instead of rolling you own function.
Smoothly running animations depends on the clients machine. No matter how fairly you code, you will never be satisfied the way your animation runs on a 128 MB Ram system.
Here is how you can scroll using jQuery:
$(document).scrollTop("50");
You might also want to try out AutoScroll Plugin.
you can use jfunc function to do this.
use jFunc_ScrollPageDown and jFunc_ScrollPageUp function.
http://jfunc.com/jFunc-Functions.aspx.
Since you've tagged the question as 'jquery', why don't you try something like .animate()? This particular jquery function is designed to smoothly animate all sorts of properties, including numeric CSS properties as well as scroll position.
the numbers are hardcoded, but the idea is to move item by item (and header is 52px) and when is down, go back
let elem = document.querySelector(".spfxBirthdaysSpSearch_c7d8290b ");
let lastScrollValue = 0
let double_lastScrollValue = 0
let scrollOptions = { top: 79, left: 0, behavior: 'smooth' }
let l = console.log.bind(console)
let intScroll = window.setInterval(function() {
double_lastScrollValue = lastScrollValue //last
lastScrollValue = elem.scrollTop // after a scroll, this is current
if (double_lastScrollValue > 0 && double_lastScrollValue == lastScrollValue){
elem.scrollBy({ top: elem.scrollHeight * -1, left: 0, behavior: 'smooth' });
} else {
if (elem.scrollTop == 0){
elem.scrollBy({ top: 52, left: 0, behavior: 'smooth' });
} else {
elem.scrollBy(scrollOptions);
}
}
}, 1000);
Here's another take on this, using requestAnimationFrame. It gives you control of the scroll time, and supports easing functions. It's pretty robust, but fair warning: there's no way for the user to interrupt the scroll.
// Easing function takes an number in range [0...1]
// and returns an eased number in that same range.
// See https://easings.net/ for more.
function easeInOutSine(x) { return -(Math.cos(Math.PI * x) - 1) / 2; }
// Simply scrolls the element from the top to the bottom.
// `elem` is the element to scroll
// `time` is the time in milliseconds to take.
// `easing` is an optional easing function.
function scrollToBottom(elem, time, easing)
{
var startTime = null;
var startScroll = elem.scrollTop;
// You can change the following to scroll to a different position.
var targetScroll = elem.scrollHeight - elem.clientHeight;
var scrollDist = targetScroll - startScroll;
easing = easing || (x => x);
function scrollFunc(t)
{
if (startTime === null) startTime = t;
var frac = (t - startTime) / time;
if (frac > 1) frac = 1;
elem.scrollTop = startScroll + Math.ceil(scrollDist * easing(frac));
if (frac < 0.99999)
requestAnimationFrame(scrollFunc);
}
requestAnimationFrame(scrollFunc);
}
// Do the scroll
scrollToBottom(document.getElementById("data"), 10000, easeInOutSine);

Categories

Resources