Why is this counting down after reaching the target? - javascript

I wanted to have a counter that only activates when actually on the screen. I've managed to mangle this together from other examples I've found.
HTML:
<div>Scroll Down</div>
<span class="count">200</span>
CSS:
div {
height:800px;
background:red;
}
h1 {
display:none;
}
Javascript:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
}
});
DEMO:
https://jsfiddle.net/76d57vjL/
The problem is, it reaches 200 and then counts back down to 0 but I want it to just stay at 200. I can't seem to figure out whats actually causing it though.

The problem was that you were creating more than 1 animation, so going back to 1 after starting the count, i fixed it with a flag, but probably you could make something with the heights to check that out.
Here's the fix with the flag: https://jsfiddle.net/uc0av8fh/
var flag = true;
$(window).scroll(function() {
$('#scroll-to');
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT-wH) , wS);
if (wS > (hT+hH-wH)){
$('.count').each(function () {
if(!flag) return;
//console.log();
flag = false;
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
return 1;
}
});
});
}
});

Related

Comma between numbers script

I have tried endless solutions that I have found for this on these forums and none that I have found work or I am simply putting it in the wrong place. I am trying to force commas for thousand and millions places. Any suggestions and placement would be appreciated.
Thank you.
jQuery(window).scroll(startCounter);
function startCounter() {
var hT = jQuery('.counter').offset().top,
hH = jQuery('.counter').outerHeight(),
wH = jQuery(window).height();
if (jQuery(window).scrollTop() > hT+hH-wH) {
jQuery(window).off("scroll", startCounter);
jQuery('.counter').each(function () {
var $this = jQuery(this);
jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 4000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
}
});
});
}
}
Assuming you would want to comma seperate values by hunders,thousands,millions,...
You may do:
let num = 9876543210;
console.log(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
// or
console.log((num).toLocaleString());
// or
console.log(new Intl.NumberFormat('en-US', {}).format(num));

Stop Javascript from running backwards once it finishes

I'm currently working on a Counter that shows some stats for my Homepage.
Here's the Script I'm using:
$('.count-1, .count-2, .count-3, .count-4').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Now I only want to run this animation if the counter comes in the screen ... So I got this Script:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.class').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
// run this if .class gets in viewpoint
} else {
// run this else
}
});
});
});
So I put both of 2 scripts together to this:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.count-1, .count-2, .count-3, .count-4').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
} else {
}
});
});
});
Now if I scroll down on my page, the counter starts running when it gets in the screen (which is exakly what I wanted) BUT when the counter finishes, the counter starts to count backwards untill .count-1, .count-2 ... is at 1. And even if I scroll up and down again ... the counter still stays at 1. Sometimes the 1 changes to a 2 or 3 but than quickly goes down to a 1 again.
Here's the snippet:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.count-1, .count-2, .count-3, .count-4').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
} else {
}
});
});
});
/* just for some scrolling */
#container {
margin-top: 1000px;
margin-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll down!</p>
<div id="container">
<div class="count-1">200</div>
<div class="count-2">100</div>
<div class="count-3">50</div>
<div class="count-4">4</div>
</div>
Where is the mistake?

jQuery number counter

I'm using this jQuery snippet to animate a number counter from 0 to to the number provided in the span. Could someone show me how to modify it to get numbers to count DOWN to 0 when starting at a given value?
<span class="count">200</span>
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Something like this? I'm assuming that 'now' in the step function is just counting steps.
$('.count').each(function () {
$(this).data('start', parseInt($(this).text())).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text($(this).data(start) - now);
}
});
});
I verified this works in jsFiddle (https://jsfiddle.net/0mtht3xm/):
$('.count').each(function () {
$(this).data('start', parseInt($(this).text())).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text($(this).data('start') - Math.ceil(now));
}
});
});
There are countless different ways to create a counter that counts down to 0. This is just how I would do it:
HTML:
<span class="count">200</span>
JS:
var $count = $('.count');
var num = parseInt($count.text());
var interval = window.setInterval(updateTime, 1000);
function updateTime() {
num--;
$count.text(num.toString());
if (num <= 0) {
window.clearInterval(interval);
}
}

Reposition DIV after scrolling

I have a navigation bar that repositions after scrolling down. It works with position:fixed, but while scrolling I want it to move up like all the other content that follow on the site . I the user stops scrolling it should reposition on top:
Heres a demo:
http://jsfiddle.net/gvjeyywa/7/
But I want it to be position:absolute (especially for the scrolling on the Ipad)
http://jsfiddle.net/gvjeyywa/5/
How do i let the JS overide my CSS? Here is my JS:
var isInAction = false;
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
if (!isInAction){
isInAction = true;
$( "#navigation" ).animate({
top: "-" + $("#navigation").innerHeight() + "px"
}).delay(1000).animate({
top: "0px"
}, 800, function() {
isInAction = false;
});
}
}
lastScrollTop = st;
});
In the first look i think it's impossible but after some tries this code was created.
I spent long time to write this code and use several techniques and hope to be helpful.
Maybe there are simpler solutions too !!
var bitFlag = false;
var lastScrollTop = 0;
var timeoutId;
$navigation = $("#navigation");
$(window).scroll(function (event) {
var intWindowTop = $(window).scrollTop();
var intElementBottom = $navigation.offset().top + $navigation.innerHeight();
if (intWindowTop > lastScrollTop) {
if (!bitFlag) {
$navigation.css("position", "absolute").css("top", intWindowTop + "px");
bitFlag = true;
}
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function () {
if (intWindowTop > intElementBottom) {
intDelayTime = setTimeout(function () {
$navigation.animate({
top: intWindowTop + "px"
}, 800);
}, 500);
}
}, 100);
} else {
$navigation.css("position", "fixed").css("top", "0px");
bitFlag = false;
}
lastScrollTop = intWindowTop;
});
The }, 500); section control Delay time in milliseconds and the }, 800); section control the slide down animation speed.
Check JSFiddle Demo

Animation ( bar fills up over time ) with Jquery (Suggestion)

I would like to replicate the same functionality as at ign.com, where the indicator bar fills up over time. I got it working but I got some sync issues after a while. So i'm open to suggestions to do it from scratch (I'm beginner with all this animation stuff).
This is the code.
function GoProgressBar() {
var $lineStatus = $('.featured-articles-line-status');
$lineStatus.css('width', '0px');
$lineStatus.animate({ width: '694px' }, 12000, 'linear', GoProgressBar);
};
function GoOverlay(width, isLast, currentWidth) {
var $overlayLine = $('.status-overlay');
if (isLast) {
$overlayLine.css('width', '0px');
return;
}
if (currentWidth) {
$overlayLine.css('width', currentWidth);
$overlayLine.animate({ width: width }, 700);
} else {
$overlayLine.css('width', '0px');
$overlayLine.animate({ width: width }, 700);
}
};
function ShowNextElement() {
var $elements = $('.element'),
$overlayLine = $('.status-overlay'),
$liElements = $('#elements li'),
width;
if (currentElement === elements[elements.length - 1]) {
currentWidth = $overlayLine.width() + 'px',
width = currentWidth + $($liElements[(elements.length - 1)]).outerWidth() + 'px';
GoOverlay(width, true, currentWidth);
currentElement = elements[0];
$elements.hide();
$(currentElement).fadeIn(1000);
return;
}
i = elements.indexOf(currentElement) + 1;
var currentTab = $liElements[(i - 1)],
currentWidth = $overlayLine.width();
if (currentWidth) {
width = currentWidth + $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, currentWidth);
} else {
width = $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, false);
}
currentElement = elements[i];
$elements.hide();
$(currentElement).fadeIn(1000);
}
Thanks!
http://jqueryui.com/progressbar/
You could try this..
There are more features in addition to this,check it out.
Might come useful :)
There are a wealth of ways in which you could do this.
You should have some kind of controller to manage the show and hide.
var Application = {
show : function() {
jQuery('.application-overlay').stop().animate({ top: 40 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 1000},500);
},
hide : function() {
jQuery('.application-overlay').stop().animate({ top: -1200 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 200},500);
}
};
Then you have your triggers : Application.show();
jQuery(document).ready(function() {
jQuery('.cf-speakers .span2 a').hover(function() {
jQuery('span',this).stop().animate({ opacity: 1.0 },100);
}, function() {
jQuery('span',this).stop().animate({ opacity: 0.0 },100);
});;
jQuery('.apply-now').click(function(e) {
Application.show();
e.stopPropagation();
e.preventDefault();
});
jQuery('body').click(function(e) {
var application = jQuery('.application-overlay');
if( application.has(e.target).length === 0)
Application.hide();
});
jQuery('.gallery a').click(function(e) {
var src = jQuery(this).attr('href');
jQuery('.main-container img').hide().attr('src', src).fadeIn('fast');
jQuery('.gallery a').each(function() {
jQuery(this).removeClass('active');
});
jQuery(this).addClass('active');
e.stopPropagation();
e.preventDefault();
});
});
Your css would of course come into play also but that can be left to you!
This should give you an example of what you need .. But you're already on the right track, sometimes there is merit in reusing other people code too you know! :)

Categories

Resources