Running function on window scroll once in jQuery

2019-03-06 12:01发布

问题:

I'm creating my portfolio and I'm trying to make my skill bars load when I go to "My skills" section. I want them to do it only once, either when someone scroll to this section or goes to it straight away from the navigation. This is my code:

var skills = $('#mySkills');
  var skillsPositionTop = skills.position().top;
 $(window).on("resize scroll", function (){
      if (pageYOffset<skillsPositionTop-20 && pageYOffset>skillsPositionTop-80){
    console.log ("here is my loading script");

} });

It doesn't work when I use one instead of on, doesn't work when I created one more function on window with one inside my if statement. I was trying exit the function with return or return false as well and here, on stack overflow I found something about flag, which I didn't fully understand but I tried different combinations with it. Can someone please help me with it? I've seen there is a library for this type of effects, but there is no point of installing any just for one thing...

Edit. Console.log represens my loading code.

回答1:

You can set a namespace at .on() for resize, scroll events, use .off() within if statement to remove namespaced events.

var skills = $('#mySkills');
var skillsPositionTop = skills.position().top;
$(window).on("resize.once scroll.once", function (){
  if (pageYOffset<skillsPositionTop-20 && pageYOffset>skillsPositionTop-80) {
    $(this).off("resize.once").off("scroll.once");
    console.log ("here is my loading script");
  }
});