ztools-1.0.x-dev/js/prevent-double-click.js
js/prevent-double-click.js
(function ($, Drupal, once) {
'use strict';
Drupal.ztoolsPreventDoubleClick = {};
Drupal.ztoolsPreventDoubleClick.disableButton = function (button) {
$(button).attr('disabled', 'disabled');
};
Drupal.ztoolsPreventDoubleClick.lockButton = function (button) {
$(button).attr('ztools-locked', 'true');
};
Drupal.ztoolsPreventDoubleClick.buttonIsLocked = function (button) {
return $(button).attr('ztools-locked') === 'true';
};
Drupal.ztoolsPreventDoubleClick.withoutDisable = function (button) {
return $(button).attr('data-ztools-without-disable') === 'true';
};
Drupal.ztoolsPreventDoubleClick.isUserClick = function (event) {
return event.originalEvent !== undefined;
};
Drupal.behaviors.ztoolsPreventDoubleClick = {
attach: function (context, settings) {
$(once('ztools', '[data-ztools-prevent-double-click="true"]', context)).each(function (i, button) {
$(button).on('click', function (event) {
var form = button.form;
// If the form is not valid don't disable or lock the submit button
if (!form.checkValidity || form.checkValidity()) {
if (Drupal.ztoolsPreventDoubleClick.buttonIsLocked(button) && Drupal.ztoolsPreventDoubleClick.isUserClick(event)) {
event.stopPropagation();
return false;
}
else if (Drupal.ztoolsPreventDoubleClick.withoutDisable(button)) {
if (!Drupal.ztoolsPreventDoubleClick.buttonIsLocked(button)) {
setTimeout(function () {
Drupal.ztoolsPreventDoubleClick.lockButton(button);
}, 1);
}
}
else {
// We need to put this in a timeout because if you disable the button
// immediately, it prevents the submit of the form.
setTimeout(function() {
Drupal.ztoolsPreventDoubleClick.disableButton(button);
}, 1);
}
}
})
});
}
};
})(jQuery, Drupal, once);
