Search code examples
javascriptfunctionchart.jsdom-eventsonscroll

Execute 'onscroll' function only once


SEE - https://codepen.io/pranavraghaw1/pen/BaNGRXY

I'm using the onscroll event in Javascript to animate my chart, made using 'Chart.js'.

The problem is, The function gets called every time I scroll on the page.

The approach that I'm using to calculate the Position of Display(the X-position when the graph-animation will run) is :

Simple approach to call functions on scroll

One solution that I tried (for execting the function only once) is :

let run = true;  
 if (Ypos>play && run) {
   run = false;
   disp();
 }

SEE - https://codepen.io/pranavraghaw1/pen/BaNGRXY

I'm not experience in jQuery, so I'll need a solution in Javascript only.


Solution

  • your problem is here let run = true; this should be declared outside your´addEventListener´ not inside.