I have two jQuery sliders on a page. I would like to fire an event when the user has set both of them. I define “set” as “when both sliders have been idle for 3 seconds”.
Can I do something like this, or is it bad practice to create a global variable like this / are there any other problems with the code?
var globalTimer = null;
function myEvent() {
alert('Both sliders are set!');
}
$("#slider-1").slider({
stop: function(event, ui) {
clearTimeout(globalTimer);
globalTimer = setTimeout(myEvent, 3000);
}
});
$("#slider-2").slider({
stop: function(event, ui) {
clearTimeout(globalTimer);
globalTimer = setTimeout(myEvent, 3000);
}
});
You don’t need the global variable. Your code has to be contained within a
$(document).readyblock, so that the.slidermethod is called when the document is ready.That already creates a closure, in which you can declare the
globalTimervariable.When the
.sliderplugin is well-defined See bottom, you can combine the selectors, and use.slider(..)to activate the plugin for both elements:In jQuery, plugins should be defined as shown below. That allows a single plugin call to apply functionality on a all elements which match the selector. This effectively reduces code: