i have this code and i want it to count in percentage, not in numbers how it is showed in the next code, how can i do it?
if someone could help me please, i'm not very good at Javascript
/* Counter - CountTo */
var a = 0;
$(window).scroll(function() {
if ($('#counter').length) { // checking if CountTo section exists in the page, if not it will not run the script and avoid errors
var oTop = $('#counter').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
},
complete: function() {
$this.text(commaSeparateNumber(this.countNum));
//alert('finished');
}
});
});
a = 1;
}
}
});
<div class="cell">
<div class="counter-value number-count" data-count="97%">1%</div>
<p class="counter-info p-small">Percentage</p>
</div>
Just add % after the text.
$this.text(Math.floor(this.countNum)+"%");
$this.text(this.countNum+"%");
$this.text(commaSeparateNumber(this.countNum)+"%");
or use css ::after (better way in my opinion because you can control the '%' style):
.counter-value::after{
content:'%';
}
And if your counter isn't percentaged - just divide it by the max value it can be and multiply by 100
The goal is to make anime.js animate just when a user scrolls and stop animation when scrolling stops. The animations are different for up and down scrolling.
Here's the current code:
var focusDown, focusUp;
var up = false, down = false, scrollPos = 0, scrollPos1;
var isScrolling;
window.addEventListener('scroll', function () {
window.clearTimeout( isScrolling );
scrollPos1 = $(window).scrollTop();
if (scrollPos1 == scrollPos) {} else {
if (scrollPos1 > scrollPos) {
up = false;
down = true;
} else {
up = true;
down = false;
}
}
scrollPos = scrollPos1;
if (down) {
focusDown = anime({
targets: '.focus-text', easing: 'linear', duration: 20000, autoplay: false,
translateX: function(el) {
return $('.focus-text').offset().left + 500;
}
});
focusDown.play();
}
if (up) {
focusUp = anime({
targets: '.focus-text', easing: 'linear', duration: 20000, autoplay: false,
translateX: function(el) {
return $('.focus-text').offset().left - 500;
}
});
focusUp.play();
}
isScrolling = setTimeout(function() {
if (focusUp && focusUp !== 'undefined') {focusUp.pause();}
if (focusDown && focusDown !== 'undefined') {focusDown.pause();}
}, 200);
}, false);
jsfiddle link
Any help appreciated!
It does not work because you call window.clearTimeout( isScrolling ); on each scroll event. Suppose the browser fires two scroll events in 100ms then the first animation doesn't get paused because the function to pause it is cleared by the clearTimeout called by the second event.
In the end you could do without pausing, just adjust the duration and translation values
var duration = 200;
var offset = 50;
/*...*/
if (down) {
focusDown = anime({
targets: '.focus-text', easing: 'linear', duration: duration,
translateX: function(el) {
return $('.focus-text').offset().left + offset;
}
});
}
if (up) {
focusUp = anime({
targets: '.focus-text', easing: 'linear', duration: duration,
translateX: function(el) {
return $('.focus-text').offset().left - offset;
}
});
}
/*...*/
I'm stuck with my page scroll effects.
This is what I've got so far - https://codepen.io/DCRSLG/pen/jzYJeY
$(document).ready(function($) {
//variables
var hijacking = $('body').data('hijacking'),
animationType = $('body').data('animation'),
delta = 0,
scrollThreshold = 5,
actual = 1,
animating = false;
//DOM elements
var sectionsAvailable = $('.cd-section'),
verticalNav = $('.cd-vertical-nav'),
prevArrow = verticalNav.find('a.cd-prev'),
nextArrow = verticalNav.find('a.cd-next');
//check the media query and bind corresponding events
var MQ = deviceType(),
bindToggle = false;
bindEvents(MQ, true);
$(window).on('resize', function() {
MQ = deviceType();
bindEvents(MQ, bindToggle);
if (MQ == 'mobile') bindToggle = true;
if (MQ == 'desktop') bindToggle = false;
});
function bindEvents(MQ, bool) {
if (MQ == 'desktop' && bool) {
//bind the animation to the window scroll event, arrows click and keyboard
if (hijacking == 'on') {
initHijacking();
$(window).on('DOMMouseScroll mousewheel', scrollHijacking);
} else {
scrollAnimation();
$(window).on('scroll', scrollAnimation);
}
prevArrow.on('click', prevSection);
nextArrow.on('click', nextSection);
$('a[href*="#"]').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var target = $(this).attr('href');
$(target).velocity('scroll', {
duration: 3000,
offset: 0,
easing: 'ease-in-out',
mobileHA: false
});
});
$(document).on('keydown', function(event) {
if (event.which == '40' && !nextArrow.hasClass('inactive')) {
event.preventDefault();
nextSection();
} else if (event.which == '38' && (!prevArrow.hasClass('inactive') || (prevArrow.hasClass('inactive') && $(window).scrollTop() != sectionsAvailable.eq(0).offset().top))) {
event.preventDefault();
prevSection();
}
});
//set navigation arrows visibility
checkNavigation();
} else if (MQ == 'mobile') {
//reset and unbind
resetSectionStyle();
$(window).off('DOMMouseScroll mousewheel', scrollHijacking);
$(window).off('scroll', scrollAnimation);
prevArrow.off('click', prevSection);
nextArrow.off('click', nextSection);
$(document).off('keydown');
}
}
function scrollAnimation() {
//normal scroll - use requestAnimationFrame (if defined) to optimize performance
(!window.requestAnimationFrame) ? animateSection(): window.requestAnimationFrame(animateSection);
}
function animateSection() {
var scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
windowWidth = $(window).width();
sectionsAvailable.each(function() {
var actualBlock = $(this),
offset = scrollTop - actualBlock.offset().top;
//according to animation type and window scroll, define animation parameters
var animationValues = setSectionAnimation(offset, windowHeight, animationType);
transformSection(actualBlock.children('div'), animationValues[0], animationValues[1], animationValues[2], animationValues[3], animationValues[4]);
(offset >= 0 && offset < windowHeight) ? actualBlock.addClass('visible'): actualBlock.removeClass('visible');
});
checkNavigation();
}
function transformSection(element, translateY, scaleValue, rotateXValue, opacityValue, boxShadow) {
//transform sections - normal scroll
element.velocity({
translateY: translateY + 'vh',
scale: scaleValue,
rotateX: rotateXValue,
opacity: opacityValue,
boxShadowBlur: boxShadow + 'px',
translateZ: 0,
}, 0);
}
function initHijacking() {
// initialize section style - scrollhijacking
var visibleSection = sectionsAvailable.filter('.visible'),
topSection = visibleSection.prevAll('.cd-section'),
bottomSection = visibleSection.nextAll('.cd-section'),
animationParams = selectAnimation(animationType, false),
animationVisible = animationParams[0],
animationTop = animationParams[1],
animationBottom = animationParams[2];
visibleSection.children('div').velocity(animationVisible, 1, function() {
visibleSection.css('opacity', 1);
topSection.css('opacity', 1);
bottomSection.css('opacity', 1);
});
topSection.children('div').velocity(animationTop, 0);
bottomSection.children('div').velocity(animationBottom, 0);
}
function scrollHijacking(event) {
// on mouse scroll - check if animate section
if (event.originalEvent.detail < 0 || event.originalEvent.wheelDelta > 0) {
delta--;
(Math.abs(delta) >= scrollThreshold) && prevSection();
} else {
delta++;
(delta >= scrollThreshold) && nextSection();
}
return false;
}
function prevSection(event) {
//go to previous section
typeof event !== 'undefined' && event.preventDefault();
var visibleSection = sectionsAvailable.filter('.visible'),
middleScroll = (hijacking == 'off' && $(window).scrollTop() != visibleSection.offset().top) ? true : false;
visibleSection = middleScroll ? visibleSection.next('.cd-section') : visibleSection;
var animationParams = selectAnimation(animationType, middleScroll, 'prev');
unbindScroll(visibleSection.prev('.cd-section'), animationParams[3]);
if (!animating && !visibleSection.is(":first-child")) {
animating = true;
visibleSection.removeClass('visible').children('div').velocity(animationParams[2], animationParams[3], animationParams[4])
.end().prev('.cd-section').addClass('visible').children('div').velocity(animationParams[0], animationParams[3], animationParams[4], function() {
animating = false;
if (hijacking == 'off') $(window).on('scroll', scrollAnimation);
});
actual = actual - 1;
}
resetScroll();
}
function nextSection(event) {
//go to next section
typeof event !== 'undefined' && event.preventDefault();
var visibleSection = sectionsAvailable.filter('.visible'),
middleScroll = (hijacking == 'off' && $(window).scrollTop() != visibleSection.offset().top) ? true : false;
var animationParams = selectAnimation(animationType, middleScroll, 'next');
unbindScroll(visibleSection.next('.cd-section'), animationParams[3]);
if (!animating && !visibleSection.is(":last-of-type")) {
animating = true;
visibleSection.removeClass('visible').children('div').velocity(animationParams[1], animationParams[3], animationParams[4])
.end().next('.cd-section').addClass('visible').children('div').velocity(animationParams[0], animationParams[3], animationParams[4], function() {
animating = false;
if (hijacking == 'off') $(window).on('scroll', scrollAnimation);
});
actual = actual + 1;
}
resetScroll();
}
function unbindScroll(section, time) {
//if clicking on navigation - unbind scroll and animate using custom velocity animation
if (hijacking == 'off') {
$(window).off('scroll', scrollAnimation);
(animationType == 'catch') ? $('body, html').scrollTop(section.offset().top): section.velocity("scroll", {
duration: time
});
}
}
function resetScroll() {
delta = 0;
checkNavigation();
}
function checkNavigation() {
//update navigation arrows visibility
(sectionsAvailable.filter('.visible').is(':first-of-type')) ? prevArrow.addClass('inactive'): prevArrow.removeClass('inactive');
(sectionsAvailable.filter('.visible').is(':last-of-type')) ? nextArrow.addClass('inactive'): nextArrow.removeClass('inactive');
}
function resetSectionStyle() {
//on mobile - remove style applied with jQuery
sectionsAvailable.children('div').each(function() {
$(this).attr('style', '');
});
}
function deviceType() {
//detect if desktop/mobile
return window.getComputedStyle(document.querySelector('body'), '::before').getPropertyValue('content').replace(/"/g, "").replace(/'/g, "");
}
function selectAnimation(animationName, middleScroll, direction) {
// select section animation - scrollhijacking
var animationVisible = 'translateNone',
animationTop = 'translateUp',
animationBottom = 'translateDown',
easing = 'ease',
animDuration = 800;
switch (animationName) {
case 'gallery':
animDuration = 1500;
if (middleScroll) {
animationTop = 'scaleDown.moveUp.scroll';
animationVisible = 'scaleUp.moveUp.scroll';
animationBottom = 'scaleDown.moveDown.scroll';
} else {
animationVisible = (direction == 'next') ? 'scaleUp.moveUp' : 'scaleUp.moveDown';
animationTop = 'scaleDown.moveUp';
animationBottom = 'scaleDown.moveDown';
}
break;
}
return [animationVisible, animationTop, animationBottom, animDuration, easing];
}
function setSectionAnimation(sectionOffset, windowHeight, animationName) {
// select section animation - normal scroll
var scale = 1,
translateY = 100,
rotateX = '0deg',
opacity = 1,
boxShadowBlur = 0;
if (sectionOffset >= -windowHeight && sectionOffset <= 0) {
// section entering the viewport
translateY = (-sectionOffset) * 100 / windowHeight;
switch (animationName) {
case 'gallery':
if (sectionOffset >= -windowHeight && sectionOffset < -0.9 * windowHeight) {
scale = -sectionOffset / windowHeight;
translateY = (-sectionOffset) * 100 / windowHeight;
boxShadowBlur = 400 * (1 + sectionOffset / windowHeight);
} else if (sectionOffset >= -0.9 * windowHeight && sectionOffset < -0.1 * windowHeight) {
scale = 0.9;
translateY = -(9 / 8) * (sectionOffset + 0.1 * windowHeight) * 100 / windowHeight;
boxShadowBlur = 40;
} else {
scale = 1 + sectionOffset / windowHeight;
translateY = 0;
boxShadowBlur = -400 * sectionOffset / windowHeight;
}
break;
}
} else if (sectionOffset > 0 && sectionOffset <= windowHeight) {
//section leaving the viewport - still has the '.visible' class
translateY = (-sectionOffset) * 100 / windowHeight;
switch (animationName) {
case 'gallery':
if (sectionOffset >= 0 && sectionOffset < 0.1 * windowHeight) {
scale = (windowHeight - sectionOffset) / windowHeight;
translateY = -(sectionOffset / windowHeight) * 100;
boxShadowBlur = 400 * sectionOffset / windowHeight;
} else if (sectionOffset >= 0.1 * windowHeight && sectionOffset < 0.9 * windowHeight) {
scale = 0.9;
translateY = -(9 / 8) * (sectionOffset - 0.1 * windowHeight / 9) * 100 / windowHeight;
boxShadowBlur = 40;
} else {
scale = sectionOffset / windowHeight;
translateY = -100;
boxShadowBlur = 400 * (1 - sectionOffset / windowHeight);
}
break;
}
} else if (sectionOffset < -windowHeight) {
translateY = 100;
switch (animationName) {
case 'gallery':
scale = 1;
break;
}
} else {
//section not visible anymore
translateY = -100;
switch (animationName) {
case 'gallery':
scale = 1;
break;
}
}
return [translateY, scale, rotateX, opacity, boxShadowBlur];
}
});
/* Custom effects registration - feature available in the Velocity UI pack */
//gallery
$.Velocity
.RegisterEffect("scaleDown.moveUp", {
defaultDuration: 1,
calls: [
[{
translateY: '-10%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '-100%'
}, 0.60],
[{
translateY: '-100%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveUp.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '-100%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '-100%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveUp", {
defaultDuration: 1,
calls: [
[{
translateY: '90%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '0%'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveUp.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '0%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveDown", {
defaultDuration: 1,
calls: [
[{
translateY: '10%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '100%'
}, 0.60],
[{
translateY: '100%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveDown.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '100%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '100%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveDown", {
defaultDuration: 1,
calls: [
[{
translateY: '-90%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '0%'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
I'm trying to get it so the Dots on the right hand side can be a reference to scroll down to each section like this:
https://codyhouse.co/demo/vertical-fixed-navigation/index.html
$('a[href*="#"]').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var target = $(this).attr('href');
$(target).velocity('scroll', {
duration: 3000,
offset: 0,
easing: 'ease-in-out',
mobileHA: false
});
});
I can get it to work using the above code providing I disable data-hijacking on the scroll, does anyone know of a way to get this to work while keep data-hijacking enabled?
I have made a few scroll functions with anchor tags that when the anchor reaches the top of the page, it then triggers certain animations. Super simple stuff.
But for some reason in Safari, as soon as the first anchor point is reached, they all fire at the same time. This defeats the point.
I think it may be the way I am checking for when the user scrolls, but I think someone with a bit more knowledge than me can help.
I have attached a snippet for you to look at -
CODE -
//SCROLL TO TRIGGER CHARTS
$(function() {
var oTop = $('#chartAnchor').offset().top - window.innerHeight;
var chartHidden = true;
$(window).scroll(function() {
var pTop = $('body').scrollTop();
if ((pTop > oTop) && (chartHidden)) {
chartHidden = false;
makeCharts();
}
});
});
//TOTAL VIEWS COUNTER FUNCTIONS
$(function() {
var oTop = $('#stat-anchor').offset().top - window.innerHeight;
var chartHidden = true;
$(window).scroll(function() {
var pTop = $('body').scrollTop();
if ((pTop > oTop) && (chartHidden)) {
chartHidden = false;
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 1500,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
var finalNum = this.countNum.toString().replace(/(\d+)(\d{6})/, '$1' + ',' + '$2');
finalNum = finalNum.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
$this.text(finalNum);
ready = false;
}
});
});
}
});
});
//GENDERS COUNTER FUNCTIONS
$(function() {
var oTop = $('#gender-anchor').offset().top - window.innerHeight;
var chartHidden = true;
$(window).scroll(function() {
var pTop = $('body').scrollTop();
if ((pTop > oTop) && (chartHidden)) {
$('.male').addClass('left');
$('.female').addClass('right');
chartHidden = false;
$('.counter2').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 1500,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
var finalNum = this.countNum;
$this.text(finalNum + '%');
}
});
});
//Affinity & Age Animations
$('.affinity-info').css('opacity', '1');
$('.user-age').css('opacity', '1');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<a class="view-demos" id="chartAnchor" href="mailto:adrian#hsm.co.za">Enquire for more stats</a>
<div class="mobile-stat-wrap" id="stat-anchor">
<img class="device-icon" src="img/mobileIcon.png">
<p class="device-icon-head">Mobile</p>
<p id="mobile-stat" class="device-stat">7,302,872</p>
</div>
<div class="counter-wrap col-12">
<p class="stats-heading-small">Total Views</p>
<div class="counter" data-count="16400708">0</div>
</div>
<div class="gender-wrap">
<div class="center-wrap">
<p class="stats-heading-small">Gender</p>
<div class="male">
<img class="gender-icon" src="img/male.png">
<p class="gender-stat counter2" id="male-stat" data-count="55">%</p>
</div>
<div class="female">
<img class="gender-icon" src="img/female.png">
<p class="gender-stat counter2" id="female-stat" data-count="45">%</p>
<span id="gender-anchor"></span>
</div>
</div>
<div class="affinity-info-wrap col-12">
<img class="affinity-info" src="img/affinityInfo.png">
<img class="user-age" src="img/userAge.png">
</div>
</div>
Don't subtract window height to get the location of your anchor.
$(function() {
//Don't need to subtract the top offset by window innerHeight
//var oTop = $('#gender-anchor').offset().top - window.innerHeight;
var oTop = $('#gender-anchor').offset().top;
var chartHidden = true;
$(window).scroll(function() {
var pTop = $('body').scrollTop();
if ((pTop > oTop) && (chartHidden)) {
$('.male').addClass('left');
$('.female').addClass('right');
chartHidden = false;
$('.counter2').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 1500,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
var finalNum = this.countNum;
$this.text(finalNum + '%');
}
});
});
//Affinity & Age Animations
$('.affinity-info').css('opacity', '1');
$('.user-age').css('opacity', '1');
}
});
});
I've searched a lot these days but i didn't manage to solve my problem.
I have the script below which is a simple counter, that counts some stats starting from 0. It starts when my page loads. I would like to fire this event when i scroll to a specific div or id, but only once. I saw a lot examples with .one() method etc. but i didn't find out the proper solution.
Here is my script.
<script type="text/javascript">
$.fn.jQuerySimpleCounter = function( options ) {
var settings = $.extend({
start: 0,
end: 100,
easing: 'swing',
duration: 500,
complete: ''
}, options );
var thisElement = $(this);
$({count: settings.start}).animate({count: settings.end}, {
duration: settings.duration,
easing: settings.easing,
step: function() {
var mathCount = Math.ceil(this.count);
thisElement.text(mathCount);
},
complete: settings.complete
});
};
$('.number1').jQuerySimpleCounter({end: 14,duration: 2899});
$('.number2').jQuerySimpleCounter({end: 350,duration: 3300});
$('.number3').jQuerySimpleCounter({end: 450,duration: 4000});
$('.number4').jQuerySimpleCounter({end: 7,duration: 2500});
</script>
So what should i add to trigger it after reaching a certain div or id...?
I managed to find a "good" solution that works for me. doing the below "not so good" thing. :) Thanks Nikolas for your help.
<script type="text/javascript">
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
var one = $('.tworow').position().top;
var two = $('.endrow').position().top;
if (scroll > one & scroll < two) {
$.fn.jQuerySimpleCounter = function( options ) {
var settings = $.extend({
start: 0,
end: 100,
easing: 'swing',
duration: 500,
complete: ''
}, options );
var thisElement = $(this);
$({count: settings.start}).animate({count: settings.end}, {
duration: settings.duration,
easing: settings.easing,
step: function() {
var mathCount = Math.ceil(this.count);
thisElement.text(mathCount);
},
complete: settings.complete
});
};
$('.number1').jQuerySimpleCounter({end: 14,duration: 2899});
$('.number2').jQuerySimpleCounter({end: 350,duration: 3300});
$('.number3').jQuerySimpleCounter({end: 450,duration: 4000});
$('.number4').jQuerySimpleCounter({end: 7,duration: 2500});
};
});
When the scroll reaches a certain div it starts, and after that i put another div where the event should end, controlling it with an if condition. Now the area of the page that triggers the event is a very small "area" between 2 divs.
This should give you the result you're looking for:
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
var one = $('element').position().top;
var count = 0;
if (scroll > one) {
var newCount = count + 1;
if (newCount === 1) {
//do something
};
};
});