I am using jQuery 1.8.
I have a series of checkboxes that a user can check to get information on particular product. When the box is check, a function is called and loads the product info into a div. CURRENTLY, the function fires immediately after each click. So, if the visitor checks all five boxes, the ajax call will be made five times.
What I want is for the function to fire after a certain period of time once the visitor stops clicking. The function should fire only once. The purpose of the delay is to limit the number of calls and create a smoother user experience.
Here is my HTML:
<input type='checkbox' class='SomeClass' data=prodid='1'> 1
<input type='checkbox' class='SomeClass' data=prodid='2'> 2
<input type='checkbox' class='SomeClass' data=prodid='3'> 3
<input type='checkbox' class='SomeClass' data=prodid='4'> 4
<input type='checkbox' class='SomeClass' data=prodid='5'> 5
<div id='ProductInfoDiv'></div>
Here is my pseudo JavaScript:
// set vars
$Checkbox = $('input.SomeClass');
$ProductInfoDiv = $('div#ProductInfoDiv');
// listen for click
$Checkbox.click(getProductInfo);
// check which boxes are checked and load product info div
getProductInfo = function() {
// create list of product id from boxes that are checked
var QString = $Checkbox.filter(":checked");
// LOAD THE PRODUCT DIV
$ProductInfoDiv.load('SomePage.cfm?'+QString);
}
So, where do I put the delay? How do ensure that the function only fires ONCE?
setTimeout with clearTimeout will accomplish this. Each click would do
var timeout = null;
$(element).click(function(){
if(timeout)
{
clearTimeout(timeout);
}
timeout = setTimeout([some code to call AJAX], 500);
})
On each click, if there is a timeout it is cleared and restarted at 500 milliseconds. That way, the ajax can never fire until the user has stopped clicking for 500 milliseconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With