Home > Blockchain >  How do I remove the background after setTimeOut() is complete?
How do I remove the background after setTimeOut() is complete?

Time:12-09

Without either padding, height or width, the content disappears after a time of 5000 as it's meant to be. But once I include any of the following properties, the background remains after setTimeOut(), only the text disappears. How can I fix this? You can run my code to see what I mean.

const msg = "Welcome";
document.getElementById("alarmmsg").innerHTML = msg;

setTimeout(function(){
document.getElementById("alarmmsg").innerHTML = '';
}, 4000);
.Javascript-Message-disappears-1{
    width: 100px;
    height: auto;
    background-color: crimson;
    text-align: center;
    position: absolute;
    top: calc(100vh - 70px);
    padding: 20px;
    box-sizing: border-box;
}
<body>
        <div  id="alarmmsg"></div>
        
</body>

CodePudding user response:

Remove the class that's styling the background from the element along with the message update, within your setTimeout()

const msg = "Welcome";
document.getElementById("alarmmsg").innerHTML = msg;

setTimeout(function(){
    document.getElementById("alarmmsg").innerHTML = '';
    document.getElementById("alarmmsg").classList.remove("Javascript-Message-disappears-1");
}, 4000);
.Javascript-Message-disappears-1{
    width: 100px;
    height: auto;
    background-color: crimson;
    text-align: center;
    position: absolute;
    top: calc(100vh - 70px);
    padding: 20px;
    box-sizing: border-box;
}
        <div  id="alarmmsg"></div>
        

CodePudding user response:

Is there any reason you can't do the following?

const alarm = document.getElementById("alarmmsg");

setTimeout(function () {
  alarm.innerHTML = "";
  alarm.style.background = "none";
}, 4000);

Or if you need to remove the element:

const alarm = document.getElementById("alarmmsg");

setTimeout(function () {
  alarm.style.display = "none";
}, 4000);

I'm assuming because it is a 'welcome' message that you won't need to toggle the message back on again before the page is reloaded.

CodePudding user response:

Try this so you can completely remove the element from the DOM:

const msg = "Welcome";
document.getElementById("alarmmsg").innerHTML = msg;

setTimeout(function() {
  document.getElementById("alarmmsg").remove();
}, 4000);
.Javascript-Message-disappears-1 {
  width: 100px;
  height: auto;
  background-color: crimson;
  text-align: center;
  position: absolute;
  top: calc(100vh - 70px);
  padding: 20px;
  box-sizing: border-box;
}
<div  id="alarmmsg"></div>

  • Related