Richard
Richard

Reputation: 32909

Fire event on checkbox .change() but *after* a checkbox appears checked?

I'm using jQuery to capture a click event on a checkbox and call a function.

My issue is this: the function I'm calling is relatively slow to execute, and so the user sees a visible delay before the checkbox appears to be checked, which makes the interface appear sluggish and inelegant.

This fiddle demonstrates the problem: http://jsfiddle.net/ZkUgq/4/ or code here:

function slowFunction() { 
   var mystr;
    for (var i = 0; i < 5000000; i++) { 
        mystr += ' ';
    }
}
$('#mycheckbox').click(function() { 
   slowFunction();
});

Is there a way I can change things so that the click event still fires slowFunction, but doesn't delay the appearance of a tick in the checkbox?

Ideally what I'd like is an onChecked event for the checkbox, but I don't know if that exists.

NB: the reason I'm asking is because I'm using an iPhone Checkbox, and the relatively slow function that I call when my checkboxes changes makes it look sluggish, and not iPhone-like at all :)

Upvotes: 3

Views: 3021

Answers (2)

redDevil
redDevil

Reputation: 1919

settimeout will defer the slowFunction call until the checkbox check event is fired.

$('#mycheckbox').click(function() {     
       setTimeout(slowFunction,500); 
});

Upvotes: 1

Matthew Abbott
Matthew Abbott

Reputation: 61599

Why not defer it with setTimeout?

$("#mycheckbox").click(function() {
    setTimeout(slowFunction, 100);
}

Which will invoke your function 100ms after the click event occurs... adjust to suit.

Upvotes: 7

Related Questions