Home > Software engineering >  Add class after 2 second and remove after 7 second in loop
Add class after 2 second and remove after 7 second in loop

Time:06-01

I want to add a class after 2 seconds and remove it after 7 seconds and when remove again add the class after 2 seconds and remove it after 7 seconds

$(document).ready(function() {
    function removeAddClass1() {
      $(".video_title").removeClass("level_show");
      setTimeout(removeAddClass1, 7000);
    }
    removeAddClass1();

    function removeAddClass2() {
      $(".video_title").addClass("level_show");
      setTimeout(removeAddClass2, 2000);
    }
    removeAddClass2();
});
.video_title {
  color: red;
}
.video_title.level_show {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 >Video title</h2>

CodePudding user response:

I suggest using CSS keyframes for this:

.video_title {
  color: red;
  animation: levelshow 7000ms infinite;
}

@keyframes levelshow {
  29.9% {
    color: red;
  }
  30% {
    color: green;
  }
  99.9% {
    color: green;
  }
  100% {
    color: red;
  }
}
<h2 >Video title</h2>

Here is how you do it with JavaScript:

window.onload = () => {
  document.querySelector(".video_title").classList.remove("level_show")
  toggleSequence()
  setInterval(toggleSequence, 7000);
}

function toggleSequence() {
  setTimeout(() => {
    document.querySelector(".video_title").classList.toggle("level_show");
  }, 2000)
  setTimeout(() => {
    document.querySelector(".video_title").classList.toggle("level_show");
  }, 7000)
}
.video_title {
  color: red;
}

.video_title.level_show {
  color: green;
}
<h2 >Video title</h2>

CodePudding user response:

.video_title {
    color: red;
    animation: levelshow 7000ms infinite;
}
@keyframes levelshow {
    29.9% {
        color: red;
    }
    30% {
        color: green;
    }
    99.9% {
        color: green;
    }
    100% {
        color: red;
    }
}
  • Related