specified class but jQuery jumps element

0

I have this HTML

<div class="slider">

 <div class="slide ativa">
   <img class="fade" src="http://funerariasaopedro.net.br/novo/_img/_banner/_site/bg_1.jpg"/><span>Esteé1</span></div><divclass="slide">
   <img class="fade" src="http://funerariasaopedro.net.br/novo/_img/_banner/_site/bg_2.jpg"/><span>Esteé2</span></div><nav><buttonclass="anterior">Anterior</button>
  <button class="proximo">Próximo</button>
 </nav>

</div>

And this jQuery

$(document).ready(function(e) {

  function startslider() {  

    ativa = $("div.slider div.ativa")

    if (!$(ativa).next().length) {
      ativa = blocos[0]
    }

     $(ativa)
        .removeClass("ativa")
        .next()
        .addClass("ativa")

     setTimeout(startslider, 5000)
  }

  setTimeout(startslider, 5000)

})

The idea here is to go through ONLY divs whose class is .slide . You can not run the NAV tag.

But it seems that jQuery is setting the object NAV also to the class .slide .

How to fix this? The impression I have is that

$ (active) .next (). length

It will always be true because there is no comparison with .slide to know that of div.slide

    
asked by anonymous 06.05.2018 / 02:31

1 answer

4

That's what's happening. This .next() below is catching the next element after .ativa , in this case, nav :

$(ativa)
.removeClass("ativa")
.next()
.addClass("ativa")

What you need to do is to check that .next in if is div.slide :

if (!$(ativa).next("div.slide").length) {

But you must also do a different treatment, so you need to enter else to return the .ativa class to the first element with .first() .

Here's how it would look:

$(document).ready(function(e) {

   function startslider() {  
   
      ativa = $("div.slider div.ativa")
   
      if (!$(ativa).next("div.slide").length) {
         // remove a classe do último
         $(ativa)
         .removeClass("ativa")
   
         // adiciona a classe no primeiro
         $("div.slider div.slide")
         .first()
         .addClass("ativa")
      }else{
         $(ativa)
         .removeClass("ativa")
         .next()
         .addClass("ativa")
      }
   
      setTimeout(startslider, 5000)
   }
   
   setTimeout(startslider, 5000)

})
div.ativa{
   display: block;
}

.slide{
   display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="slider">

 <div class="slide ativa">
   <img class="fade" src="http://funerariasaopedro.net.br/novo/_img/_banner/_site/bg_1.jpg"/><span>Esteé1</span></div><divclass="slide">
   <img class="fade" src="http://funerariasaopedro.net.br/novo/_img/_banner/_site/bg_2.jpg"/><span>Esteé2</span></div><nav><buttonclass="anterior">Anterior</button>
  <button class="proximo">Próximo</button>
 </nav>

</div>
    
06.05.2018 / 04:00