问题
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