Answer the question
In order to leave comments, you need to log in
How to apply a CSS property during a specific event?
I am creating a chat window. And it has an icon "The interlocutor is typing".
So, if the interlocutor starts typing, then a certain event is called in the script. If it continues to print, this event repeats every 5 seconds.
Task: if the event happened and repeats every 5 seconds - show the icon. And if it didn't happen within 5 seconds, hide the icon.
Now it's implemented like this: During the first event, a CSS class is added to the container. The time of the last event is stored. Then every second a check is started whether 5 seconds have passed since the last event. If yes, the CSS class is removed.
But I'm sure there is an easier way (perhaps through CSS itself). But what?
Answer the question
In order to leave comments, you need to log in
Somehow you went from the opposite, make it easier - upon arrival of the event (print), set the acc. block CSS class (if not already set) and create a new setTimeout, while clearing the old one, if roughly something like this:
function onTypingReceived() {
if( !$('#typing').hasClass('typing') ) { $('#typing').addClass('typing'); } // Добавляем класс
clearTimeout(window.typeTimer);
window.typeTimer = setTimeout(function() {
$('#typing').removeClass('typing'); // Убираем класс через 5 секунд
}, 5000);
}
CSS alone cannot accomplish this task. If only the animation is used by keyframe. But class management will rely on JS anyway. Since it is meant to work with a timer. CSS is not designed for this.
On js, I would recommend using a timer with a certain delay. I didn’t quite understand the meaning of why to call a check every second, if you can start the reverse timer with the required delay. By pressing the user on the keyboard, reset the timer and restart using the saved identifier. Upon completion of the countdown, change the class of a specific block. Everything seems to me quite simple, there is nowhere to simplify further. And play around with CSS animation depending on your preferences.var id = setInterval(fn, delay);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question