0

I have two classes:

<div class="currentWeather"></div>
<div class="weeklyWeather"></div>

I am trying to toggle between them so every 10 seconds it will show one of these classes and hide the other and so on.

setInterval(function(){

$(".currentWeather, .weeklyWeather").toggleClass("currentWeather weeklyWeather");

}, 3000);

But this just switches the class names....Is toggle not what I am looking for?

user979331
  • 11,039
  • 73
  • 223
  • 418

1 Answers1

1
//CSS Class:

.mask{
    display: none;
}

//setInterval callback function to add and remove mask class
setInterval(function(){
   //You can check if the element has the class with .hasClass
   if($('.currentWeather').hasClass('mask'){
       $('.currentWeather').removeClass('mask');
       $('.weeklyWeather').addClass('mask');
   }else{
        $('.currentWeather').addClass('mask');
        $('.weeklyWeather').removeClass('mask');
   }

   //Or you can just .toggleClass
    $('.currentWeather').toggleClass('mask');
    $('.weeklyWeather').toggleClass('mask');

}, 3000);

//And your HTML would have to have one of these divs with class mask initially
   <div class="currentWeather"></div>
   <div class="weeklyWeather mask"></div>
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
  • why not just use `toggleClass` for both and remove the `if` statement? – No Name Aug 14 '18 at 18:39
  • Would toggleClass have a smoother transition? – user979331 Aug 14 '18 at 18:43
  • @BojanSrbinoski I'm just used to coding it that way, I added to my answer to reflect the `.toggleClass()` way of doing it, but I'm pretty sure that `.toggleClass()` is doing the same thing I am doing in my `if - else` – Ryan Wilson Aug 14 '18 at 18:45
  • @RyanWilson Agreed, I was just wondering if there was a specific reason for not using it. It looks better too imo ;) – No Name Aug 14 '18 at 18:46
  • @BojanSrbinoski I just like to make things harder on myself, old habits, lol – Ryan Wilson Aug 14 '18 at 18:47
  • @LawrenceCherone That's another option as well. Great part about programming, there is typically more than one way to accomplish a goal. – Ryan Wilson Aug 14 '18 at 18:48
  • @RyanWilson tbh I just found out about toggleClass.....wish I heard about it sooner – No Name Aug 14 '18 at 18:49
  • @BojanSrbinoski Yeah, I knew about it, I just forget about some methods if I don't use them enough. That's what happens when you start getting old. :P – Ryan Wilson Aug 14 '18 at 18:49
  • How would I add a transition to this? – user979331 Aug 14 '18 at 19:00
  • @user979331 Please see this post (https://stackoverflow.com/questions/11179238/toggleclass-animate-jquery), IMO, Dario's answer will be most helpful – Ryan Wilson Aug 14 '18 at 19:25