Search code examples
javascriptcreateelement

How to prevent this warning message from revealing multiple times


As you can see in the image, the warning shows up whenever I trigger the click eventListener, naturally. But how can I make it show up only once. Thanks in advance.

image

function eventListeners() {
form.addEventListener("submit", addTodo)
}
function showAlert(type, message) {
    const alert = document.createElement("div")
    alert.className = `alert alert-${type} d-inline p-1`
    alert.setAttribute("style", "border-radius: 2rem")
    alert.textContent = message
    form.appendChild(alert)
    setTimeout(function () {
        alert.remove()
    }, 1000)   
}


Solution

  • // Not a good solution.

    Try this :

    let isAlertBeingShown = false 
    
    function eventListeners() {
    form.addEventListener("submit", addTodo)
    }
    function showAlert(type, message) {
        if( isAlertBeingShown ) {
           //Do not show alert. Simply return.
           return; 
          // or you can do alert.remove here instead of return.
    
        }
        const alert = document.createElement("div")
        alert.className = `alert alert-${type} d-inline p-1`
        alert.setAttribute("style", "border-radius: 2rem")
        alert.textContent = message
        form.appendChild(alert);
        isAlertBeingShown = true;
        setTimeout(function () {
            alert.remove();
            isAlertBeingShown = false;
        }, 1000)   
    }