Is there a way for me to trigger this animation to play as soon as the element comes into the view

I'm looking to create a counting animation that triggers when the element scrolls onto the page, rather than animating right when the page loads. I attempted to use $(window).scroll(function () but struggled to make it work with an if statement that would start the animation when the element appears between the top and bottom of the screen.

HTML:

<div class="sectiontitle">
    <h2>Project Stats</h2>
    <span class="headerLine"></span>
</div>
<div id="projectFacts" class="sectionClass">
    <div class="fullWidth eight columns">
        <div class="projectFactsWrap ">
            <div class="item wow fadeInUpBig animated animated" data-number="12" style="visibility: visible;">
                <i class="fa fa-briefcase"></i>
                <p id="number1" class="number">12</p>
                <span></span>
                <p>Projects Completed</p>
            </div>
            <div class="item wow fadeInUpBig animated animated" data-number="55" style="visibility: visible;">
                <i class="fa fa-smile-o"></i>
                <p id="number2" class="number">55</p>
                <span></span>
                <p>Satisfied Clients</p>
            </div>
            <div class="item wow fadeInUpBig animated animated" data-number="359" style="visibility: visible;">
                <i class="fa fa-coffee"></i>
                <p id="number3" class="number">359</p>
                <span></span>
                <p>Cups of Coffee</p>
            </div>
            <div class="item wow fadeInUpBig animated animated" data-number="246" style="visibility: visible;">
                <i class="fa fa-camera"></i>
                <p id="number4" class="number">246</p>
                <span></span>
                <p>Photos Taken</p>
            </div>
        </div>
    </div>
</div>

CSS:

 .sectionClass {
  padding: 20px 0px 50px 0px;
  position: relative;
  display: block;
}

.fullWidth {
  width: 100% !important;
  display: table;
  float: none;
  padding: 0;
  min-height: 1px;
  height: 100%;
  position: relative;
  line-height: 50px;
}

.sectiontitle {
  background-position: center;
  margin: 30px 0 0px;
  text-align: center;
  min-height: 20px;
}

.sectiontitle h2 {
  font-size: 30px;
  color: #222;
  margin-bottom: 0px;
  padding-right: 10px;
  padding-left: 10px;
}


.headerLine {
  width: 160px;
  height: 2px;
  display: inline-block;
  background: #101F2E;
}
...

JQuery:

    <script>
$.fn.jQuerySimpleCounter = function( options ) {
        var settings = $.extend({
            start:  0,
            end:    100,
            easing: 'swing',
            duration: 400,
            complete: ''
        }, options );
...
</script>

Answer №1

Make sure to take a look at this JSFiddle demo.

To prevent the animation from getting reset every time there is a scroll event, include two conditions in your code.

var hasAnimationStarted = false;
$(window).scroll(function(){
    var scrollPosition = $(window).scrollTop();
    if(scrollPosition > 0 && !hasAnimationStarted){
       $('#number1').jQuerySimpleCounter({end: 12,duration: 3000});
       $('#number2').jQuerySimpleCounter({end: 55,duration: 3000});
       $('#number3').jQuerySimpleCounter({end: 359,duration: 2000});
       $('#number4').jQuerySimpleCounter({end: 246,duration: 2500});
       hasAnimationStarted = true;
    }
});

Answer №2

Be sure to take a look at the CodePen link

var executed = true;

$(window).scroll(function () {

    var $mainElement = $('#projectFacts'),
        windowScroll = $(window).scrollTop(),
        mainContainer = $mainElement.position().top;

    if (windowScroll > mainContainer && executed) {

        $('#number1').jQuerySimpleCounter({end: 12, duration: 3000});
        $('#number2').jQuerySimpleCounter({end: 55, duration: 3000});
        $('#number3').jQuerySimpleCounter({end: 359, duration: 2000});
        $('#number4').jQuerySimpleCounter({end: 246, duration: 2500});

        executed = false;

    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ion-List seamlessly integrates with both ion-tabs and ion-nav components, creating a cohesive and dynamic user interface

On my homepage, there is an ion-list. Sometimes (not every time), when I select an item in this list or navigate to the register page using "this.app.getRootNav().push("ClienteCadastroPage")", and then select an input in the registerPage or descriptionPage ...

What strategies can I implement to prevent position: absolute from obscuring my content?

I am currently experiencing an issue with my Google Map loading within a tab. The container div has the position set to absolute. Although the map displays correctly, I am encountering a problem where it covers any content I try to place underneath it. My ...

Having trouble adjusting the font color and font style of the text in a hamburger menu

I'm currently working on customizing the text displayed on my hamburger menu. Below are the codes I've tried to adjust the text and font-family of the hamburger menu, but it seems like these changes only affect the color of the icon, not the actu ...

Using JQuery to animate a div tag and automatically hide it after a specific duration

I'm attempting to create an animation where a div tag moves left 300px, hides after 3 seconds, and then repeats the process every 8 seconds. However, my current code only runs the animation once and doesn't repeat the entire process. Below is the ...

Deactivate the action triggered by a jQuery click event

$('document').ready(function(){ //textoverflow($('.content'),100); $('span').click(function(){ //disable textoverflow function & output full text }); }); function textoverflow(ele, num){ ele.each( ...

jQuery - auto reload page after clicking

My jQuery method is designed to execute a specific action when the button with the ID 'add' is clicked: $(function () { $('#add').on('click', function () { $('#headline').text("Hurra!"); }); }) While obs ...

Converting JSON into HTML format

Seeking guidance as a developer tasked with rendering JSON to HTML on a webpage. I've taken over for someone else and, despite feeling somewhat in over my head, have managed to build the basic structure using Catalyst/Template Toolkit and Dojo. Now th ...

Is it possible to transmit JSON data using a standard link in ASP.NET MVC?

Is it possible to send a JSON string to an ASP.NET-MVC controller action without using jQuery and Ajax? When I post using Ajax, I can pass information into the data parameter as a JSON string. ...

best method for embedding javascript code within html (within a script tag)

In my quest to create dynamic HTML using jQuery and insert it into a specific div on my website, I encountered an issue. Specifically, I am attempting to generate an anchor element where both the href and label are determined by JavaScript variables. Here ...

Ways to show confirmation when the user presses the back browser button?

Similar Question: How can I capture the browser's back button event using JavaScript? In my application, I am looking to implement a feature where only certain scripts (Text1.php, Text2.php, and Text3.php) will trigger a confirmation box when the ...

Determine the exact beginning and ending positions of a word when dividing it using Javascript

After creating a special function that breaks down a word based on spaces while keeping punctuation marks intact, I was able to achieve the desired result. function tokenizeUtterance( utterance ) { let spilittedUserText = utterance.toString().match( /[& ...

Include a name in the set_values function using Rvest

I'm currently working on scraping data from this website. I have a code written in rvest for login, but each time the page refreshes, the form name changes. library(rvest) loginpage <- "https://demo.glpi-project.org/" pagesession <- html_sess ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

What is the correct way to apply CSS to center text within a colored box that has rounded corners?

I want to use CSS to create an image that resembles the one in the attached .png file. The box should be approximately 280x30 pixels in size. Can anyone guide me on how to achieve this? Thank you for any assistance! enter image description here ...

What is the best way to show input choices once an option has been chosen from the 'select class' dropdown menu?

When it comes to displaying different options based on user selection, the following HTML code is what I've been using: <select class="form-control input-lg" style="text-align:center"> <option value="type">-- Select a Type --</opti ...

Is it possible to show the Display Center within the dropdown menu?

Hello everyone, this is my first time posting on stackoverflow. I have a question about centering the select options. Could someone please take a look at the image attached and let me know if it's possible? <select multiple="multiple" nam ...

PubNub's integration of WebRTC technology allows for seamless video streaming capabilities

I've been exploring the WebRTC sdk by PubNub and so far, everything has been smooth sailing. However, I'm facing a challenge when it comes to displaying video from a client on my screen. Following their documentation and tutorials, I have writte ...

What is the best way to insert a value into the span element generated by the Tag-it plugin?

Currently working with the Tag-it plugin to generate tags. Since the tags are created using spans, I'm curious to learn how I can assign a value to a tag created by the plugin? Seeking assistance from someone knowledgeable in this area. Thank you! ...

Implement a dynamic loading feature using AJAX, pushState, and Jekyll for a

In an effort to create a standard template for our studio's Jekyll sites development, I am aiming to implement page animation transitions. My plan involves loading different content from each page using AJAX and utilizing pushState to update the URL a ...

I am struggling to add a column in HTML for this specific layout. Can someone please provide me with guidance on how to proceed?

This is the code I have: <div class="container"> <div class="row"> <div class="col-md-4"> <img src="https://s21466.pcdn.co/wp-content/uploads/2018/02/Logo-FIVB-Liga-nacija-1.jpg" width="500" height="640"> </div ...