I am having some issue with document.on('click') event, The first time I open the form it binds the 'click' event to the document but it does not execute it which is what I expect. But when I close the form and try to open it again, The document binds the 'click' event and executes it right away. I was wondering if there is any way to solve this issue. Right now I am using the setTimeout(...) function as a hacky way to solve this issue but I am looking for a better way to fix it.
initXXXXForm = function() {
var $form = $('.zzzz'),
$formOpen = $('.xxxx'),
$formClose = $( '.yyyy' ),
$formMask = $('.wwww'),
toggleForm = function() {
if ($form.hasClass('active') === true) {
// close form
$form.removeClass('active');
$formMask.removeClass('active');
$(document).off('click'); // remove event on document to close form
}
else {
// open form
$form.addClass('active');
$formMask.addClass('active');
// bind close event when clicking outside form, set short timeout so this click event doesn't interfere with others
setTimeout(function() {
$(document).on('click', function(e) {
if ($(e.target).closest('.xxxx-form').length === 0 ) {
$(this).off('click');
toggleForm();
}
});
}, 100);
}
};
$formOpen.on('click', function() {
toggleForm();
});
}