How can I run Bootstrap Alert multiple times?

I am using the Bootstrap alert system, but I encountered a problem. My Alert appears when the button is pressed, and then the setTimeout function works and my alert does not appear after 1 second. But the problem is here, the alert part does not appear again when I make a successful or incorrect login. I want my alert to appear on every successful or incorrect login. Thanks advance for your answers. (ı don’t want Jquery, only Vanilla JavaScript.) Codepen.io: https://codepen.io/BerkayAkgurgen/pen/xxEmQLo (All Code)

function showAlert(type, message) {
  if (alert == null) {
    alert = document.createElement("div");
    alert.className = `alert alert-${type}`;
    alert.id = "alertID";
    alert.textContent = message;
    firstCardBody.appendChild(alert);
    alert.style.marginTop = "1rem";
  } else {
    alert.className = `alert alert-${type}`;
    alert.textContent = message;
  }
  setTimeout(function myFunction2() {
    document.getElementById("alertID").style.display = 'none';
  }, 1000)
};

Add this line of code after else:

      document.getElementById("alertID").style.display = 'block';

Like this:

function showAlert(type, message) {
    if (alert == null) {
        alert = document.createElement("div");
        alert.className = `alert alert-${type}`;
        alert.id = "alertID";
        alert.textContent = message;
        firstCardBody.appendChild(alert);
        alert.style.marginTop = "1rem";
    } else {
    /*** If the element is there remove the none value ***/
      document.getElementById("alertID").style.display = 'block';
/*** END ***/

    }
    setTimeout (function myFunction2() {
         document.getElementById("alertID").style.display = 'none'; 
    }, 1000)
};

I have removed for you the redundant code in the else also.

PS:
Just as an advice, showAlert is now dependent on firstCardBody. Think on how you can do to provide firstCardBody as a dependency so you can reuse showAlert in other places.
This is obviously optional but a skill you need to master in this industry.

1 Like

Hey Bro Thanks but . The codes you deleted were important. I have a question, How did adding this give me the solution?

You can put it back as you like. I only removed it because was not relevant to that alert box and also I assumed that the function does only one thing. (I have not had a look through the rest of the code :upside_down_face:) I am not sure I understand the question. Give it another shot.

Ok, so when the function showAlert is called second time, the else statement is run (because the alert variable is not null) and sets the css value from none to block, making the html element visible.

You can add some console.log there with the date/time so you can see what is called and when or use debugger; statements to see exactly what the variables hold and why things work in a certain way.

1 Like