3

I have a simple question as I'm not to deep into JS coding.

What is wrong with the following code-snippet and why isn't it executing as expected. (-> loading the charts as soon as they come into view)

var waypoint  = new Waypoint({
  element: document.querySelector("#chartcontainer"),
  handler: function() {
    $(".chart").easyPieChart({
      scaleColor: false,
      lineWidth: 20,
      lineCap: "butt",
      barColor: "#9b0000",
      trackColor: "#ecf0f1",
      size: 160,
      animate: 1500
    });
    $(".count").each(function() {
      var $this = $(this);
      $({ Counter: 0 }).animate({ 
        Counter: $this.text() 
      },{
        duration: 1500,
        easing: "swing",
        step: function() {
          $this.text(Math.ceil(this.Counter));
        }
      });
    });
  }
});

I don't understand what I have done wrong with my script. An explanation would be helpful for (maybe) future problems.

For the whole snippet and all the used libraries & frameworks, check out the corresponding codepen: https://codepen.io/toxicterror/pen/EJPjEQ

1 Answers1

1

Waypoint actually fires when you scroll past an element. Your pen is most likely not tall enough to allow you to scroll up and down, therefore triggering the Waypoint -> EasyPieChart interaction.

I forked your pen and provided a demo that shows that your code actually works : https://codepen.io/anon/pen/VOmVrJ

I simply added these lines to your body CSS to see that it actually works :

  min-height:10000px;
  overflow-y:scroll;

In a real life scenario, you most likely won't need it since you're planning on scrolling past this content.


EDIT :

If you use the offset property of Waypoint, you can actually make sure it gets both triggered on page load, and on page scroll. Try using it like this :

var waypoint  = new Waypoint({
  element: document.querySelector("#chartcontainer"),
  offset: $("#chartcontainer").height(),
  handler: function() {
    ...

By setting it to the height of the container, you make sure it is fully visible before triggering the animation.

Bernard Saucier
  • 2,240
  • 1
  • 19
  • 28