• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Need help placing multiple js animations on one page.

Contributor ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

Morning,

I have three animated numbers I am wanting to place on a page. One needs a $ sign and the others don't. How can I call different js for the other two that don't need the $ in front of the number? When I place all three on a page they get wacky and animate every time you scroll instead of just once when in view as well. 

Here is the one with the $.

Thank you for any help.

 

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet">
<style>
body { min-height: 100vh; }
.container {margin: 0px auto;  font-family: 'Roboto', sans-serif; max-width: 640px; text-align: center;}
.count676 { height: 100px;   color: #0091b3; text-align: center;; font-size: 100px; font-weight: 200; margin: 0 auto;}
</style>
<style>

</style>
</head>

<body>
  
  <div class="container">
   
  <div class="count676"></div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>

 <script>

function isInView(elem) {

var docViewTop = $(window).scrollTop();

var docViewBottom = docViewTop + $(window).height() - 200;

var elemTop = $(elem).offset().top;

return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));

}

$(window).scroll(function(){

 

if (isInView($('.count676'))) {

 

  jQuery(function($) {

    $('.count676').countTo({

        from: 0,

        to: 676,

        speed: 1300,

 

    });

});

 

 

$(window).off('scroll');

}

})

 

</script>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36251023-1']);
  _gaq.push(['_setDomainName', 'jqueryscript.net']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src=('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
	<script>
	/**
 * A jQuery plugin to display counter.
 * @author: Akhtar Husain <dev.akhtarhusain@gmail.com>
 * @version: 1.0
 */
(function($) {
    $.fn.countTo = function(options) {
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.from - options.to) / loops;
		Number.prototype.formatMoney = function(c, d, t){
		var n = this, 
			c = isNaN(c = Math.abs(c)) ? 2 : c, 
			d = d == undefined ? "." : d, 
			t = t == undefined ? "," : t, 
			s = n < 0 ? "-" : "", 
			i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), 
			j = (j = i.length) > 3 ? j % 3 : 0;
		   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
		 };

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value -= increment;
                loopCount++;
				var newVal = value.formatMoney(options.decimals, options.separator) + 'M';

$(_this).html('$' + newVal);

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 100,
        to: 10,
        speed: 500,
        refreshInterval: 100,
        decimals: 0,
        onUpdate: null,
        onComplete: null,
		separator: '.'
    };
})(jQuery);
</script>
	 



</body>
</html>

 

 

TOPICS
Code , How to

Views

1.3K

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

LEGEND , Feb 11, 2020 Feb 11, 2020

See if the code below helps:

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> 
<title>Animated Stats</title>
<style>
.spacer {
height: 900px;
background-color: #f2f2f2;
text-align: center;
}
.stats {
display: flex;
justify-content: space-around;
}
.stats > div {
width: 25%;
}
.stats h3 {
font-size: 55px;
font-weight: 400;
text-align: center;
color: #0091b3;
}
.footer {
background-color: #f2f2f2;
text-align: center;
padding: 20px;
}
</style>
 </head>
 <body>
<div class="spacer"><h
...

Votes

Translate

Translate
Community Expert ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

The latest jQuery is version 3.4, not 1.2.  It's best to use the latest stable release if possible. 

https://code.jquery.com/

 

<script   src="https://code.jquery.com/jquery-3.4.1.min.js"   integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="   crossorigin="anonymous"></script>

 

I suggest you test new scripts on a plain vanilla page that contains no other competing scripts.   When you get that working, then add the other scripts one at a time to ensure there are no conflicts.

 

Nancy O'Shea— Product User, Community Expert & Moderator
Alt-Web Design & Publishing ~ Web : Print : Graphics : Media

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

Thanks Nancy didn't even see that it was calling an older version. Do you have any suggestion on how to get multiple scripts on the page like what I was looking into doing? One animation without the $?

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

See if the code below helps:

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> 
<title>Animated Stats</title>
<style>
.spacer {
height: 900px;
background-color: #f2f2f2;
text-align: center;
}
.stats {
display: flex;
justify-content: space-around;
}
.stats > div {
width: 25%;
}
.stats h3 {
font-size: 55px;
font-weight: 400;
text-align: center;
color: #0091b3;
}
.footer {
background-color: #f2f2f2;
text-align: center;
padding: 20px;
}
</style>
 </head>
 <body>
<div class="spacer"><h2>Spacer</h2></div>

<section class="stats">
<div class="stat1"><h3>$0M</h3></div>
<div class="stat2"><h3>0</h3></div>
<div class="stat3"><h3>0</h3></div>
</section>

<footer class="footer"><h2>Footer</h2></footer>


<script>
var isInViewport = function (elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top  < (window.innerHeight -50)
);
};

// assign divs where content appears to variables
const stat1 = document.querySelector('.stat1');
const stat2 = document.querySelector('.stat2');
const stat3 = document.querySelector('.stat3');


window.addEventListener('scroll', function (event) {

// stat1	
if (isInViewport(stat1)) {
statNum1(x);
}

// stat2
if (isInViewport(stat2)) {
statNum2(x);
}

// stat3
if (isInViewport(stat3)) {
statNum3(x);
}


});
// end window scroll function


let x = 0;


// statNum1
var isScrolled1 = false;
function statNum1(x) {
if(!isScrolled1){
setInterval(function(){ 
x++;
if(x > 676) {
return false;
}
stat1.innerHTML = `<h3>$${x}M</h3>`;	
}, 5);
}
isScrolled1 = true;
}

// statNum2
var isScrolled2 = false;
function statNum2(x) {
if(!isScrolled2){
setInterval(function(){ 
x++;
if(x > 250) {
return false;
}
stat2.innerHTML = `<h3>${x}</h3>`;
}, 5);
}
isScrolled2 = true;
}

// statNum3
var isScrolled3 = false;
function statNum3(x) {
if(!isScrolled3){
setInterval(function(){ 
x++;
if(x > 400) {
return false;
}
stat3.innerHTML = `<h3>${x}</h3>`;
}, 5);
}
isScrolled3 = true;
}
</script>

</body>
 </html>

 

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

Excellent! Thats what I was looking for. So just to understand, instead of the $ sign being called by java it's being called through the text inside each div and the 0 is a placeholder? What an excellent way of accomplishing this. Thanks so much.

 

<section class="stats">
<div class="stat1"><h3>$0M</h3></div>
<div class="stat2"><h3>0</h3></div>
<div class="stat3"><h3>0</h3></div>
</section>

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

Yes, initially you set a placeholder, then replace the placeholder text with the 'dynamic' number so x counts from 0 to 676 and then stops. You could start at a higher number by setting x to something other than 0.

let x = 0;

 

Initial placeholder text gets replaced in the 'stat1 class <div> ' as number increases to 676:

stat1.innerHTML = `<h3>$${x}M</h3>`;	

 

You could use let y = 0; for your second number and let z = 0; for you third number, depends how complicated things get and if you want to start all 3 numbres at different values.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

One more question. One of my stats has a decimal. 11.4M. How can I add that to stat 2?

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

Try the below for your stat2 decimal number:

 

// statNum2
let y = 0;
var isScrolled2 = false;
function statNum2(y) {
if(!isScrolled2){
setInterval(function(){
y = y += 0.1;
if(y > 11.4) {
return false;
}
stat2.innerHTML = `<h3>${y.toFixed(1)}M</h3>`;
}, 50);
}
isScrolled2 = true;
}

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Feb 11, 2020 Feb 11, 2020

Copy link to clipboard

Copied

LATEST

Thank you!!! Worked perfect.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines