Search code examples
javascripttransitionfade

Why doesn't my function remove an element after a delay?


I'm struggling to make a notification show on press of a button and then hide after a time. Nearly all of the resources I found implement a solution based on jQuery, but I am not using a JS framework and am not willing to to so just for the sake of this. What I got so far:

function notify() {
  var success = document.getElementById("success");

  success.innerHTML = 'ok';
  success.style.opacity = '1';
  setTimeout(function () {
    success.classList.add('fade');
  }, 5000);
}
#successposition {
  position: absolute;
  bottom: 0;
  left: 50%;
  margin-bottom: 100px;
}
#success {
  z-index: 12;
  position: relative;
  left: -50%;
  opacity: 0;
  border-radius: 5px;
  background-color: rgba(38, 213, 26, 0.5);
  padding: 15px;
  color: #000;
  font-size: 0.8em;
}
#success.fade {
  opacity: 0;
  transition: 0.5s opacity;
}
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css" />
    <meta name="viewport" content="width=device-width">
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="UTF-8" />
    <script src="notify.js"></script>
  </head>
  <body>
    <button onclick="notify()">click me</button>
    <div id="successposition"><div id="success"></div></div>
  </body>
</html>

Sadly, this only shows the notification on click, but it never goes away. Can anybody help?


Solution

  • Your inline styles override your class-based styles. Switch to just classes:

    function notify() {
      var success = document.getElementById("success");
    
      success.innerHTML = 'ok';
      success.classList.add('show'); // <-- HERE
    
      setTimeout(function () {
        success.classList.remove('show'); // <-- HERE
      }, 2000);
    }
    #successposition {
      position: absolute;
      bottom: 0;
      left: 50%;
      margin-bottom: 100px;
    }
    #success {
      z-index: 12;
      position: relative;
      left: -50%;
      opacity: 0;
      border-radius: 5px;
      background-color: rgba(38, 213, 26, 0.5);
      padding: 15px;
      color: #000;
      font-size: 0.8em;
      opacity: 0;
      transition: 0.5s opacity; /* <-- HERE */
    }
    #success.show {
        opacity: 1;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <link rel="stylesheet" href="style.css" />
        <meta name="viewport" content="width=device-width">
        <meta name="viewport" content="initial-scale=1.0">
        <meta charset="UTF-8" />
        <script src="notify.js"></script>
      </head>
      <body>
        <button onclick="notify()">click me</button>
        <div id="successposition"><div id="success"></div></div>
      </body>
    </html>