Issue with the Animated Skill Bar not functioning properly when scrolling

I've been trying to implement an animated skill bar in my Portfolio using JQuery, but I'm facing some challenges. Despite following various tutorials, the code doesn't seem to work as expected. I've tried calculating section scroll position and window scroll position, changing parent divs and child divs, but the outcome remains unchanged. Here is My Updated Code

$(document).ready(function() {
  var skillBar = $('.skill-body');
  $(window).scroll(function() {
    var SkillLocation = $("#Education-Skill").offset().top;
    var scrollLocation = $(this).scrollTop();

    skillBar.each(function() {
      if (SkillLocation <= scrollLocation) {
        $(this).find('.inner-skill-bar').animate({
          width: $(this).attr('data-percent')
        }, 2000);
      }
    });
  });
});
.outer-skill-bar {
  height: 26px;
  width: 100%;
  border: 1px solid black;
}

.inner-skill-bar {
  height: 100%;
  width: 0%;
  background: lightcoral;
  border-right: 0.5px solid rgb(146, 136, 136);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" id="Education-Skill">
  <div class="row">
    <div class="col-md-6 skill" id="skill">
      <div class="all-skill">

        <div class="my-skill">
          <div class="skill-head d-flex">
            <i class="fab fa-html5 fa-lg"></i>
            <p>HTML5</p>
          </div>
          <div class="skill-body d-flex" data-percent="90%">
            <div class="outer-skill-bar">
              <div class="inner-skill-bar"></div>
            </div>
            <div class="percent">
              <p class="skill-value">90%</p>
            </div>
          </div>

        </div>
        <!--my-skill-->
        <div class="my-skill">
          <div class="skill-head d-flex">
            <i class="fab fa-css3-alt fa-lg"></i>
            <p>CSS3</p>
          </div>
          <div class="skill-body d-flex" data-percent="80%">
            <div class="outer-skill-bar">
              <div class="inner-skill-bar"></div>
            </div>
            <div class="percent">
              <p class="skill-value">80%</p>
            </div>
          </div>
        </div>
        <!--my-skill-->

      </div>
      <!--all skill-->
    </div>
    <!--col-->
  </div>
  <!--row-->
</div>
<!--Container-->

Answer №1

If you want to trigger the animation when a specific element appears on your screen, you can adjust the skillPosition variable to start it at the right time. In this particular case, I set it to - 100, but feel free to customize it according to your needs:

$(document).ready(function(){
var skillBar = $('.skill-body');
$(window).scroll(function(){
var SkillLocation = $("#Education-Skill").offset().top;
var scrollLocation = $(this).scrollTop();

skillBar.each(function(){
if(SkillLocation - 100 <= scrollLocation)
{
$(this).find('.inner-skill-bar').animate({width:$(this).attr('data-percent')}, 2000);
}
});
});
});
.vertical-offset {
  width: 100%;
  height: 250px;
}

.outer-skill-bar{
height: 26px;
width: 100%;
border: 1px solid black;
}
.inner-skill-bar{
height: 100%;
width: 0%;
background: lightcoral;
border-right: 0.5px solid rgb(146, 136, 136);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="vertical-offset">Scroll down...</div>
<div class="container" id="Education-Skill">
<div class="row">
      <div class="col-md-6 skill" id="skill">
<div class="all-skill">

            <div class="my-skill">
              <div class="skill-head d-flex">
                <i class="fab fa-html5 fa-lg"></i>
                <p>HTML5</p>
              </div>
              <div class="skill-body d-flex" data-percent="90%">
                <div class="outer-skill-bar">
                  <div class="inner-skill-bar"></div>
                </div>
                <div class="percent">
                  <p class="skill-value">90%</p>
                </div>
              </div>

            </div> <!--my-skill-->
            <div class="my-skill">
              <div class="skill-head d-flex">
                <i class="fab fa-css3-alt fa-lg"></i>
                <p>CSS3</p>
              </div>
              <div class="skill-body d-flex" data-percent="80%">
                <div class="outer-skill-bar">
                  <div class="inner-skill-bar"></div>
                </div>
                <div class="percent">
                  <p class="skill-value">80%</p>
                </div>
              </div>
            </div> <!--my-skill-->

          </div><!--all skill-->
        </div> <!--col-->
     </div> <!--row-->
</div> <!--Container-->
<div class="vertical-offset"></div>

Answer №2

Avoid using the scroll event listener as it can negatively impact browser performance.

Instead, consider using Intersection Observer (IO) which is specifically designed for handling these types of situations. IO allows you to respond when an HTML element intersects with another or with the viewport.

For a detailed guide on how to animate an element when it comes into view, check out this page (scroll all the way down).

Here's a brief summary of what you need to do:

Start by creating a new observer:

var options = {
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

This code specifies that the callback function will be executed when your target element is fully visible in the viewport (threshold of 1). You can adjust the threshold percentage as needed.

Next, define the elements to be observed, such as the counter elements in your case:

var target = document.querySelector('.counter');
observer.observe(target);

Finally, specify what action should be taken when the element becomes visible by defining the callback function:

var callback = function(entries, observer) { 
  entries.forEach(entry => {
    // Implement your animation logic here
  });
};

If you require support for older browsers, use the official polyfill provided by w3c.

To prevent triggering the animation multiple times when an element re-enters the viewport, you can also unobserve the element once it has been animated.

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

Are you considering getting rid of a function?

I have a small function that changes a div to position:fixed after a link is clicked. $(window).load(function(){ $('#linktofreeze').click(function() { var ftop = $('#fixedbox').offset().top - $(window).scrollTop(); ...

Tips for aligning the text of a typography element in Material-UI when its parent is fixed

Introduction to Home Component const HomeComponent = ({ mode, setMode }) => { return ( <Box m={-1} sx={{overflowX:'hidden'}}> <Navber/> <Stack direction="row" spacing={2} justifyContent="space-be ...

Elevate your web design by transitioning from Bootstrap 4 to Bootstrap 5

Should I upgrade a large project from Bootstrap 4 to version 5? Will it require extensive changes in each file? After updating my project, many components have stopped working: Dropdowns Accordions and more Is this a common issue experienced by everyo ...

Safari iOS does not properly support responsive images when using srcset and sizes

I am facing an issue with the following code snippet: <img src="/img/footer/logo_white.png?v=2.0" srcset="/img/footer/logo_white.png?v=2.0 1x, /img/footer/logo_white2x.png?v=2.0 2x" > This ...

Issue with inserting data into MySQL database using Node.js (JavaScript)

I am attempting to utilize the insert function but keep encountering an error. I want to add a user's name to the user table. The function I am using is: function insert(tableName, toField, value){ connection.connect(); var queryString = "i ...

Instructions for transferring the model to an ASP.NET controller from a ASP.NET Razor view utilizing jQuery

I've created a Razor view that takes in data. Instead of using the post method directly in the Form, I'm opting to first notify the User about saving. To achieve this, I've set up a save button to trigger a jQuery function which then calls t ...

Angular.js dynamically changing ng-class based on long-polling updates to a monitored variable

Currently utilizing angular.js for my project. I am implementing long polling with a server and would like to dynamically update an element in the view, specifically one with a class of 'updated', whenever the value of build_tag is incremented. ...

Deleting items from an array in ReactJS

When retrieving a list of users from AWS Cognito, everything works flawlessly. However, the task of iterating over this array and removing users that do not match a specific Client ID is where I'm facing difficulties. What am I doing wrong in this sc ...

Angular framework does not trigger the button click event

Currently, I am in the process of creating a web app and working on designing the register page. My experience with Angular is still at a beginner level. The following code snippet is from the resiger.component.ts file: /** * To create a new User ...

Can a new :input be dynamically added to jQuery?

I have included unique input elements that do not conform to the standard HTML input types. One example is a "pinpoint image" where users can place "pins" by clicking on it. This image is created with specific HTML code like so: <div class="pinpoint"&g ...

Experience the power of Kendo UI Date Picker combined with AngularJS. When the datepicker is initialized, it starts

Check out my code snippet below: When the datepicker loads initially, it appears empty. However, if you remove ng-model from the directive template, the datepicker displays its initial value correctly. Yet, changing the selected date does not mark the fo ...

The TD border is slicing through the div and is placed on the table in IE standards, causing it

Below is the HTML code where the div is being cut by the table border when the page is in standards mode. Interestingly, if I remove the <!DOCTYPE html>, then it works fine as expected. The issue of the outside div not behaving properly on the table ...

What is the process for attaching an on-click event listener by utilizing an argument that is passed to a function in JavaScript?

These are the functions I have created: function type(message) { document.getElementById("body").innerHTML="<div id=\"textbox\" class=\"textbox\"></div><div id=\"oc\&q ...

Guide for executing Java code and displaying HTML form fields concurrently in JSP

I have created a JSP page with form fields and Java code in scriptlets. I have imported the Java code into the JSP page and created an object to call the functions of that Java class. When I run the JSP, the page remains blank until all the Java code has ...

Generate a distinct identifier for the select element ID whenever a new row of data is inserted into a table

Although my title accurately describes my issue, I believe the solutions I have been attempting may not be on the right track. I am relatively new to javascript and web development in general, so please forgive me for any lack of technical terminology. Th ...

Angular.js is throwing an error at line 13708, stating: "Error: [ng:areq] Function 'homeController' is missing or undefined."

Encountered an issue while trying to reach HomeController (module controller). Upon clicking the "home" link, an error appeared in the console stating that "HomeController is not a function; undefined. Could you advise on where I should register this cont ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Insert information into the dataString and then send it to the ajax data parameter

<script> $(document).ready(function(){ $(".check").click(function(){ $("input:checkbox[class=check]:checked").each(function () { //alert($(this).val()); //alert($(this).attr("id")); var key = $(this ...

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

issue encountered while attaching css file / css styles not rendering

Here is the css link I am using: <link rel="stylesheet" type="text/html" href="/public/assets/lib/css/style.css" /> Despite trying various solutions such as removing "rel="stylesheet"", changing to "text/html", checking paths, placing it in the pu ...