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
JavaScript
x
13
13
1
$(document).ready(function() {
2
function removeAddClass1() {
3
$(".video_title").removeClass("level_show");
4
setTimeout(removeAddClass1, 7000);
5
}
6
removeAddClass1();
7
8
function removeAddClass2() {
9
$(".video_title").addClass("level_show");
10
setTimeout(removeAddClass2, 2000);
11
}
12
removeAddClass2();
13
});
JavaScript
1
6
1
.video_title {
2
color: red;
3
}
4
.video_title.level_show {
5
color: green;
6
}
JavaScript
1
2
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<h2 class="video_title">Video title</h2>
Advertisement
Answer
This is done by javascript
and jQuery
without using CSS keyframes
.
JavaScript
1
32
32
1
// for switch class
2
const switchCls = (selector, cls) => $(selector).toggleClass(cls);
3
4
// delay and do task
5
const delay = (action, ms) => {
6
return new Promise((resolve) => {
7
const newAction = () => {
8
action();
9
resolve(action);
10
};
11
setTimeout(newAction, ms);
12
});
13
};
14
15
// ensure execution order
16
const task = (selector, cls) => {
17
const switchFn = () => switchCls(selector, cls);
18
delay(switchFn, 2000).then(action =>
19
delay(action, 7000)
20
).then(action =>
21
task(selector, cls)
22
);
23
};
24
25
// start execution
26
task('.video_title', 'level_show');
27
28
// screen timer
29
let second = 0;
30
setInterval(() => {
31
$('h1').text(`${++second} second`);
32
}, 1000);
JavaScript
1
7
1
.video_title {
2
color: red;
3
}
4
5
.video_title.level_show {
6
color: green;
7
}
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<h2 class="video_title">Video title</h2>
3
<h1>0 second</h1>