Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery addClass and removeClass with setInterval

I want to change class name every 3 seconds. Bu it doesn't work. How can I do this?

$(document).ready(function() {
        function moveClass(){
            var x = $('.liveEvents');
            x.removeClass('liveEvents');
            x.addClass('liveEventsActive');
            x.removeClass('liveEventsActive');
            x.addClass('liveEvents');
       }

        setInterval(moveClass, 3000); 
        return false;
    });
like image 452
dr.linux Avatar asked Dec 01 '22 00:12

dr.linux


2 Answers

You can do this in one line. Use toggleClass:

setInterval(function(){$('.liveEvents').toggleClass('liveEventsActive')}, 3000);

If you do your CSS correctly, you don't need to remove the liveEvents class. Just make the liveEventsActive class overwrite what you need.

like image 200
Diodeus - James MacFarlane Avatar answered Dec 04 '22 06:12

Diodeus - James MacFarlane


You're doing four things every time the function runs, which essentially takes you back to your start state:

  • Remove class liveEvents
  • Add class liveEventsActive
  • Remove class liveEventsActive
  • Add class liveEvents

You want to toggle those two classes on/off, so take a look at the .toggleClass() function. You'll also need two selectors, one to select elements with the liveEvents class and one to select elements with the liveEventsActive class.

like image 32
Anthony Grist Avatar answered Dec 04 '22 07:12

Anthony Grist