I have a convoluted scheme to interrupt a checkbox click event, so I can run some javascript/jQuery code before the click event is completed (ie. box is checked).
But, I've noticed some different behavior when applying the code in Chrome (my base browser) and Firefox (used by a smaller set of my users).
In this fiddle example , the sequence of events works fine in Chrome, but if you try the same in firefox, the programmatic .trigger('click')
does not trigger the event listener. Why? I've googled it and perhaps something to do with the $.trigger()
method?
My code:
HTML:
<input type="checkbox" id="foo"> Clicky!
<hr>
<textarea id="bar"></textarea>
<hr>
<textarea id="cons"></textarea>
JS (using jQueryUI dialog)
$("#dialog").dialog({
autoOpen: false
});
$("#foo").on('mousedown', function(e) {
e.preventDefault(); // stop mousedown propagation
$("#foo").prop('checked', false).prop("disabled", true); // disable checkbox from checking
if (!$("#foo").is(":checked")) { // if not checked, run script
// Open a modal while checkbox event is paused
$("#dialog").dialog('open').dialog({
title: "Hey! Here is a modal",
modal: 'true',
buttons: {
"OK": function() {
// run a script while modal running during checkbox pause
$("#bar").val("checkbox paused, script run");
// release checkbox disable &
// programmatically complete the check
$("#foo").prop('disabled', false);
$("#foo")[0].click();
// This click event completes and the click listener fires below in Chrome, but not on firefox? Why oh why?
$("#dialog").dialog('close');
}
}
});
}
});
$("input:checkbox").on("click", function() {
$("#cons").val("check completed!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type="checkbox" id="foo"> Clicky!
<hr>
<textarea id="bar"></textarea>
<hr>
<textarea id="cons"></textarea>
<div id="dialog">
A modal opens
</div>
Do you really need to disable the checkbox?
When you close the modal, it takes some time to change disabled
property back to false
(in Firefox). So we need to wait until the checkbox is enabled again. Otherwise the trigger 'clicks' on the disabled checkbox with no result.
Look at the snippet, I've set a timeout on the trigger and it works:
$('#bar').on('click', function() {
$("#foo").prop('disabled', true);
alert("pause"); // alert, modal, dialog all break trigger event
$("#foo").prop('disabled', false);
// wait...
setTimeout(function() {
$("#foo").trigger('click')
}, 100);
});
$("input:checkbox").on("change", function() {
$("#baz").val("check completed!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="foo">
<hr>
<button id="bar">Checker</button>
<hr>
<textarea id="baz"></textarea>
But it could be solved a different way.
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