How can I prevent additional clicks on an element until the promise from the ajax is complete?
The element itself is not a button
I want to prevent clicks on .my_button
:
$(document).on('click', '.my_button', function () {
$.ajax({
})
.done(function (data, textStatus, jqXHR) {
})
.fail(function () {
})
.always(function () {
// enable clicks again
})
});
Is it possible with bind/unbind? If so I wasn't able to find the correct syntax
CodePudding user response:
Disable the button, then enable it in the callback function.
$(document).on('click', '#my_button', function() {
let button = this;
button.disabled = true;
$.ajax({
})
.done(function(data, textStatus, jqXHR) {
})
.fail(function() {
})
.complete(function() {
button.disabled = false;
})
});
CodePudding user response:
You could simply use a flag to track whether the operation is in progress or not. For example:
let isFetching = false;
$(document).on('click', '#my_button', function () {
// return early if already running
if (isFetching) {
return;
}
// update the value
isFetching = true;
$.ajax({
})
.done(function (data, textStatus, jqXHR) {
})
.fail(function () {
})
.complete(function () {
// reset the value
isFetching = false;
})
});
Basically, rather than trying to prevent the click itself or complicate things with unbinding/re-binding, simply don't execute the operation if you're tracking that it's currently in progress.
CodePudding user response:
You can create variable with active state of your button and toggle it like this:
let isButtonEnabled = true;
$(document).on('click', '.my_button', function () {
if (!isButtonEnabled) return;
isButtonEnabled = false;
$.ajax({
})
.done(function (data, textStatus, jqXHR) {
})
.fail(function () {
})
.complete(function () {
// enable clicks again
isButtonEnabled = true;
})
});