Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
novicell/custom_forms / js / prevent-double-submit.js
Size: Mime:
(function ($, Drupal) {
  Drupal.behaviors.lockSubmit = {
    attach: function (context, settings) {
      let $button = $('input[type="submit"].custom-forms__submit');
      let $form = $button.parents('form.custom-forms');
      if ($button.length !== 0) {
        $form.on('submit', async function() {
          $button.prop('disabled', true);
          console.log('yes!');
          let enable = await enabledSubmitButton($button);
          console.log(enable);
        });
        // If ajax is triggered we add a class to tell that re-enabling it is controlled by ajax as well.
        $(document).ajaxSend(function (event, xhr, settings) {
          if (typeof settings.data === 'string' && settings.data.indexOf("_custom_form_detector") !== -1) {
            $button.addClass('ajax-callback-triggered');
          }
        });
        $(document).ajaxComplete(function (event, xhr, settings) {
          if (typeof settings.data === 'string' && settings.data.indexOf("_custom_form_detector") !== -1) {
            $button.prop('disabled', false);
            $button.removeClass('ajax-callback-triggered');
          }
        });
      }
    }
  };

  function enabledSubmitButton($button) {
    return new Promise(resolve => {
      if ($button.length !== 0) {
        // Wait 5 seconds before attempting to enable the button again.
        setTimeout(() => {
          // Only re-enable the button if it isn't controlled by ajax.
          if (!$button.hasClass('ajax-callback-triggered')) {
            $button.prop('disabled', false);
          }
          resolve(true);
        }, 5000);
      } else {
        // No button found, so we just return true to skip.
        resolve(true);
      }
    });
  }
})(jQuery, Drupal);