How can I prevent adding more classes error while somebody is repeatedly clicking on the submit button?
In Chrome Dev Tools I see that they keep being added more and more if you spam the button. I don't know how to prevent this.
function errorFunc(req, message) {
const formControl = req.parentElement;
const span = formControl.querySelector('span');
span.innerText = message;
req.className += 'error';
span.className += 'error-text';
if(req !== email) {
req.value = ' ';
} else {
req.style.color = "hsl(0, 100%, 74%)";
}
}
function successFunc(req) {
req.className += 'success';
}
You can use element.classList.add() which doesn't create duplicates.
const x = document.querySelector('.x');
x.classList.add('error');
console.log(x.className);
x.classList.add('error');
console.log(x.className);
<div class="x"></div>
ClassList is DOMTokenList and as the MDN documentation says:
Methods that modify the DOMTokenList (such as DOMTokenList.add()) automatically trim any excess Whitespace and remove duplicate values from the list.
can be done with simple use js internal classList of a element
/** @type {HTMLElement} */
let req = document.querySelector('.x');
req.classList.add('error')
this does not add the error class if it allready exists. and it's easier to remove the error class if not longer needed req.classList.remove('error') (only removes if class is present).
also you can check if the class you want to add already is existing
req.classList.has('error');
here is the manual