jquery run once .one() in viewport

。_饼干妹妹 提交于 2019-12-13 06:47:42

问题


I am making a progressbar and want it to play when it is in viewport. I got this working but the code is now executed every time and I need it to run only once. Because it creates now multiple progressbars. ;-) The code below is used in a Joomla Extension.

(function ($) {
  $(document).ready(function() {
    // Function that checks if it is in view.
    $("<?php echo '#progress' . $module->id ?>").waypoint(function() {
      // Function that makes sure it only runs once.
      // -----------I need to use .one() here but how?
       // The location of the progressbar code for now lets put a alert in.
       alert("run only once");
    }, {
      offset: '50%'
    });
  });
})(jQuery);

I have been reading up about the .one() function and how to use it in here. But I tried the examples that uses click and ready while click is not what I want but ready should do the trick but nothing worked.


回答1:


You can use $.Callbacks() with "once" as parameter.

(function ($) {
  $(document).ready(function() {

    function runOnce() {
      // Function that makes sure it only runs once.
      // -----------I need to use .one() here but how?
       // The location of the progressbar code for now lets put a alert in.
       alert("run only once");
    }

    var callbacks = $.Callbacks("once");

    callbacks.add(runOnce);
    // Function that checks if it is in view.
    $("<?php echo '#progress' . $module->id ?>").waypoint(function() {
      callbacks.fire(runOnce);
    }, {
      offset: '50%'
    });
  });
})(jQuery);


来源:https://stackoverflow.com/questions/39709512/jquery-run-once-one-in-viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!