Use jQuery to Prevent Multiple Clicks on a Button
When users interact with buttons on your web page, there's always a risk of them clicking multiple times—especially if the action takes time, such as writing to a database or sending an email. This can lead to duplicate actions, errors, or unnecessary strain on your backend.
In this tutorial, we’ll use jQuery to prevent multiple clicks on a button and give users visual feedback when the button is temporarily disabled.
The Code
Styling the Button
We’ll use CSS to visually indicate when a button is disabled, ensuring users know it’s temporarily unclickable.
Styling
.btn {
background-color: rgba(201, 71, 95, 1);
cursor: pointer;
}
.btn.disabled {
background-color: rgba(201, 71, 95, 0.8);
cursor: not-allowed;
pointer-events: none;
}
The jQuery Script
The script below disables the button on click, runs a validation check, and performs the desired action. If the action is completed or the validation fails, the button is re-enabled.
The jQuery code
$(document).ready(function() {
const disableBtn = function($btn) {
$btn.prop('disabled', true).addClass("disabled");
};
const enableBtn = function($btn) {
$btn.prop('disabled', false).removeClass("disabled");
};
$(".btn").on('click', function(e) {
e.preventDefault(); // Prevent default behavior if needed
const $currentBtn = $(this);
if ($currentBtn.prop('disabled')) {
console.log("Button is already disabled");
return false;
}
disableBtn($currentBtn);
// Example validation logic
if (!validate()) {
console.log("Validation failed");
enableBtn($currentBtn);
return;
}
// Perform actions here
console.log("Button clicked, processing...");
// Re-enable the button based on action results
setTimeout(() => enableBtn($currentBtn), 3000); // Example timeout
});
const validate = function() {
// Add validation logic
return true; // Placeholder
};
});
Summary
This simple approach prevents multiple clicks on a button while providing visual feedback to users. By combining CSS and jQuery, you can improve user experience and avoid unintended duplicate actions.
Other content that might interest you
The cornerSlider jQuery plugin
JavaScript datetime object helper functions
Calling an API from inside a loop with JavaScript
Disclaimer
As far as I know, the script within this page is functional and harmless. However I make no guarantees. I also take no responsibility for any damage you may do when using the script (the chances of any problems occuring are slim but who knows). Please use this script responsibly and judgmentally.