jane jane - 7 days ago 4
CSS Question

Show effect only when that section is reached in a website

I have a chart made using d3.js : code for chart

I have put this chart within a website.website

Problem is that in the above website ,when you scroll through the page to the "teamchart" section,I dont see the effect of the chart.When you refresh the page,you can see the chart role the effect.

I want the chart to role and show the effect,when I reach that section of the page or when I use the nav bar,click "teamchart" and reach that section.

I used the below javascript code,but its repeating it continuously :



$(document).scroll(function() {
//Basically your position in the page
var x = $(this).scrollTop();
//How far down (in pixels) you want the user to be when the effect to starts, eg. 500
var y = 500;
if (x > y) {
//Put your effect functions in here.
}
});





fiddle related to the website :My code related to website (experiment here)

Kindly help.God bless.

Answer

As i understand, your problem is the part where the animation keeps playing.

this is because every time you scroll the page, to a value greater then 500, you actually repeating your code.

Easy solution: place a flag to signal 'alreadyAnimated'

var g_pieChartAnimated=false;

$(document).scroll(function() {
  //Basically your position in the page
  var x = $(this).scrollTop();
  //How far down (in pixels) you want the user to be when the effect to starts, eg. 500
  var y = 500;
  if (!g_pieChartAnimated && (x > y)) {
      g_pieChartAnimated = true;
      //Put your effect functions in here.
  }
});

Second solution (bit faster):
is to detach the event handler once it did what you want.

function onScroll_AnimateChart() {
  //Basically your position in the page
  var x = $(this).scrollTop();
  //How far down (in pixels) you want the user to be when the effect to starts, eg. 500
  var y = 500;
  if (!g_pieChartAnimated && (x > y)) {
      $(document).off('scroll', onScroll_AnimateChart); // remove myself from the event handlers, so it won't be called again.
      //Put your effect functions in here.
  }
}

$(document).on('scroll', onScroll_AnimateChart);