I have an input that makes an ajax call on onfocus
and onblur
. The returned result from that ajax call is formatted html which is then inserted into the DOM using innerHTML
. How can I make sure that when I click this dynamically inserted button after onblur
the click event on it fires immediately rather than having to click twice?
This is what the HTML looks like
<input type="text" id="c" onfocus="resetAllItems();" onblur="resetAllItems();">
<span id="readOnlySpan">
</span>
And here is the function resetAllItems
:
function setInnerHTML (p_item,p_associated_div, p_return_value) {
// ... makes the ajax call and sets the result
// sets innerHTML like this
var ajaxResult = '<button type="button" class="chip">Dynamic Button</button>';
window[p_item] = ajaxResult;
if ( window && window[p_item]) {
if (p_associated_div && document.getElementById(p_associated_div))
document.getElementById(p_associated_div).innerHTML=ajaxResult;
if (p_return_value == 'true')
return ajaxResult;
}
}
var resetAllItems = function () {
setInnerHTML('p_item1', 'readOnlySpan', 'true');
}
The click event is attached using event delegation
document.getElementById('readOnlySpan').addEventListener('click', function (e) {
if (e.target.nodeName == 'BUTTON') {
console.log('click');
}
});
I don't have access to setInnerHTML
or resetAllItems
but I understand that I can reassign it.
I have tried solution mentioned here but does not work for me: document.activeelement returns body
I have also tried this, but only works for links and not buttons:
var ref = resetAllItems;
resetAllItems = function () {
ref.apply(this,arguments);
var e = event;
if (e.type == 'blur') {
if (isNotNull(e.relatedTarget)) {
if (e.relatedTarget.nodeName == 'A' || e.relatedTarget.nodeName == 'BUTTON') {
console.log('click');
e.relatedTarget.click();
}
}
}
}
Edit: Just to make things clearer. I've edited the question to be more specific. I suspect that reason I have to click the button twice after onblur
is becuase it does not get focus immidately. I've setup this jsFiddle to show what I mean.
Open the fiddle, focus on the input, then try to click on the button. The click event on it won't fire on first click.
Any help would be appreciated. Thanks.