Search code examples
javascriptphphtmlcsssettimeout

How to setTimeout for one of css classes of HTML element?


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 <?php if($x == 1){ echo"second"};?>"></div>
<div class="first <?php if($x == 2){ echo"second"};?>"></div>
<div class="first <?php if($x == 3){ echo"second"};?>"></div>

<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.


Solution

  • 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>