Can I set timeout that keep on hold for 3 second one of two css classes of element. The second class of the element appears if the field meets a condition. But before this class is applied I would like to set a timer that waits 3 seconds. Example:
<?php
$x = rand(1,3);
?>
<div class="first <?= if($x == 1){ echo"second"};?>"><\div>
<div class="first <?= if($x == 2){ echo"second"};?>"><\div>
<div class="first <?= if($x == 3){ echo"second"};?>"><\div>
What I need:
<script>
If class second exist
for an element then
remove/hold/pause it for
3 seconds and then run it.
<\script>
Thank you in advance.
CodePudding user response:
Since you say you are not expert in javascript and are studying php/html/css, you may try with CSS animation properties. Be aware that animation is an advanced topic in general. A better solution might be the javascript one that Mister Jojo provided.
I could understand that:
- you can only put the class in the resulting html
- you need the change to happen after 3 seconds
- the change must happen only once
- the change regards the background color
Following there is a possible implementation, based on the previous assumptions.
.first {
background-color: lightblue;
}
.second {
animation-delay: 3s;
animation-duration: 1ms;
animation-fill-mode: forwards;
animation-iteration-count: 1;
animation-name: delayChangeColor;
}
@keyframes delayChangeColor {
to {
background-color: red;
}
}
<div class="first">1</div>
<div class="first second">2</div>
<div class="first">3</div>
CodePudding user response:
what to say...?
const
divEl = document.querySelectorAll('div.first')
, random = Math.floor( Math.random() * divEl.length)
;
divEl[random].classList.add('second')
;
setInterval(_=>
{
divEl[random].classList.toggle('second')
}, 3000);
.first {
width : 4em;
height : 2em;
background : lightskyblue;
margin : .6em 1em;
}
.second {
background : coral;
}
<div class="first"></div>
<div class="first"></div>
<div class="first"></div>