juwi juwi - 2 months ago 9
CSS Question

How to flash the background of a website?

I am trying to create a function that flashes the website every time you call it.

My approach was like this:



function flashRed() {
document.body.style.animation = "redflash 0.06s 2 alternate ease-out";
}

function flashGreen() {
document.body.style.animation = "greenflash 0.06s 2 alternate ease-out"
}

@keyframes redflash {
to {
background-color: #FFCDD2;
}
}
@keyframes greenflash {
to {
background-color: #C8E6C9;
}
}

<input type="button" value="RED" onclick="flashRed()">
<input type="button" value="GREEN" onclick="flashGreen()">





But this way I can only make it flash it once, as the animation attribute is set the first time or changes.

How can I change my code, or use a different approach to make it flash as often as i want?

Answer

Add and remove the class with an timeout...

function flashRed() {
  document.body.classList.add('red')
  window.setTimeout(function() {
    document.body.classList.remove('red')
  }, 100)

}

function flashGreen() {
  document.body.classList.add('green')
  window.setTimeout(function() {
    document.body.classList.remove('green')
  }, 100)
}
@keyframes redflash {
  to {
    background-color: #FFCDD2;
  }
}
@keyframes greenflash {
  to {
    background-color: #C8E6C9;
  }
}
.red {
  animation: redflash 0.06s 2 alternate ease-out;
}
.green {
  animation: greenflash 0.06s 2 alternate ease-out;
}
<input type="button" value="RED" onclick="flashRed()" id="red">
<input type="button" value="GREEN" onclick="flashGreen()" id="green">

Comments