Duplicate toastr error messages
I am using a JavaScript library Toastr 2.1
to display temporary message input error messages. I set the parameter preventDuplicates
to true. He does not work. I still see duplicate messages when users hit the submit button quickly (clicks are faster than "timeout").
Here are my default toastr settings:
function getDefaults() {
return {
tapToDismiss: true,
toastClass: 'toast',
containerId: 'toast-container',
debug: false,
showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery
showDuration: 300,
showEasing: 'swing', //swing and linear are built into jQuery
onShown: undefined,
hideMethod: 'fadeOut',
hideDuration: 1000,
hideEasing: 'swing',
onHidden: undefined,
extendedTimeOut: 1000,
iconClasses: {
error: 'toast-error',
info: 'toast-info',
success: 'toast-success',
warning: 'toast-warning'
},
iconClass: 'toast-info',
positionClass: 'toast-top-right',
timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky
titleClass: 'toast-title',
messageClass: 'toast-message',
target: 'body',
closeHtml: '<button>×</button>',
newestOnTop: true,
preventDuplicates: true,
progressBar: false
};
}
Do I need to make any other changes to prevent duplicate error messages?
source to share
I have the same requirements as you. Below is my implementation. See if this can help you.
function hasSameErrorToastr(message){
var hasSameErrorToastr = false;
var $toastContainer = $('#toast-container');
if ($toastContainer.length > 0) {
var $errorToastr = $toastContainer.find('.toast-error');
if ($errorToastr.length > 0) {
var currentText = $errorToastr.find('.toast-message').text();
var areEqual = message.toUpperCase() === currentText.toUpperCase();
if (areEqual) {
hasSameErrorToastr = true;
}
}
}
return hasSameErrorToastr;
}
//Usage
var message = 'Error deleting user';
if (hasSameErrorToastr(message)) {
toastr.error(message, title, errorToastrOptions);
}
The code should check if there is an existing toastr error that displays the same message. I will only fire toastr.error if there is no existing instance of the same error on display. Hope this helps. The code can be refactored further, but I'll leave it in a way that makes it easier for others to understand.
source to share