foo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<table>
<tr>
<td id="tdTxtBox"><input type="text" id="txtBox"/></td>
<td id="tdChkBox"><input type="checkbox" id="chkBox"/></td>
</tr>
</table>
<script src="foo.js"></script>
</body>
</html>
foo.js
$('#txtBox').on('blur', function(){
console.log('came out of text box');
});
$('#chkBox').on('click',function(){
console.log('checked check box');
});
Normal flow: Enter a value in the text box, click on the checkbox, which actually triggers both 'blur' on the text box and 'click' on the check box. This outputs:
came out of text box
checked check box
On Changing foo.js like so:
$('#txtBox').on('blur', function(){
console.log('came out of text box');
$('#tdChkBox').html('<input type="checkbox" id="chkBox"/>');
});
$('#chkBox').on('click',function(){
console.log('checked check box');
});
This outputs:
came out of text box
It makes sense because on blur
i actually reset the #tdChkBox
with another set of dom elements, jquery looses track of the raised event click
for the checkbox(is this correct understanding?)
I found a fix for this issue in one the SO Post, to defer change of html using setTimeout
, which will let the click
event handler execute like so:
foo.js
$('#txtBox').on('blur', function(){
console.log('came out of text box');
setTimeout(function(){
$('#tdChkBox').html('<input type="checkbox" id="chkBox"/>');
},100);
});
$('#chkBox').on('click',function(){
console.log('checked check box');
});
Here lies the problem, the 100 ms for setTimeout
works, but 0 ms doesn't work. Apparently it took time T for the system to raise the click event and register it to jquery event queue. The time assigned to setTimeout
has to be greater than T.
This solution is not full proof. What if tomorrow, it takes more than 100 ms? If i increase this time to let's say 1000 ms, its a usability hit.
How to properly approach this problem? Is the understanding correct here or am i missing something fundamental?
In case this is a standard jquery/javascript problem, can someone point me in the right direction.