Skip to content

Instantly share code, notes, and snippets.

@lloydjatkinson
Created August 15, 2018 09:07
Show Gist options
  • Save lloydjatkinson/847337d17930e02c468bcb1642bd8e13 to your computer and use it in GitHub Desktop.
Save lloydjatkinson/847337d17930e02c468bcb1642bd8e13 to your computer and use it in GitHub Desktop.
/**
* Throttles the users ability to click the specified button within the specified form by disabling the button once the form is submitting.
* @param {String} formSelector The selector of the form.
* @param {String} buttonSelector The selector of the button.
* @param {Number} throttlePeriod (Optional) The amount of time in milliseconds that the button should be disabled for. Defaults to 5000.
*/
function submitFormButtonThrottle (formSelector, buttonSelector, throttlePeriod) {
document.addEventListener('DOMContentLoaded', function() {
if (!formSelector) throw new Error('Selector expected for form.');
if (!buttonSelector) throw new Error('Selector expected for form button.');
var formElement = document.querySelector(formSelector);
var buttonElement = document.querySelector(buttonSelector);
if (!formElement) throw new Error('Form element was not found.');
if (!buttonElement) throw new Error('Form button element was not found.');
var period = throttlePeriod || 5000;
formElement.addEventListener('submit', function () {
buttonElement.setAttribute('disabled', 'true');
setTimeout(function () {
buttonElement.removeAttribute('disabled');
}, period);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment