0

I've a slider and the first slide has class first-slide. When i'm in a slider, it adds the class active automatically. I want that if this slide has the class active and first-slide also, the swiper will have a height of 100vh.

When I go to the next slide, the slider won't have the class first-slide so I want the swiper height to be auto.

I'm trying to do it like this but it doesn't apply the height: auto when I go to the second slide... it doesn't work:

if ($('.slider').hasClass('first-slide', 'active')) {
  $('.swiper').css('height', '100vh')
} else {
  $('.swiper').css('height', 'auto')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="swiper">
  <div class=" swiper-wrapper ">
    <div class="slider ">
      <!-- I only put 1 slider but you understand is more than one -->
    </div>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Vander
  • 79
  • 9
  • I made you a snippet. I had to add a `"` here `class="swiper">`. Please make the snippet into a [mcve] – mplungjan May 20 '20 at 12:09
  • If you have two `.sliders`, `$('.slider').hasClass(...)` will always be querying just the first one. You need to improve your question to show when you are calling this function, examples should be self contained, as mentioned by mplungian – Ruan Mendes May 20 '20 at 12:41

1 Answers1

3

First, the documentation shows that hasClass takes a single class, not a list.

Secondly, if you have two .sliders, $('.slider').hasClass(...) will always be querying just the first one. See Get the sum of the outerHeight of all elements of the same class

I think you want to call the following code after each slide change, it looks for an active first slide and does something depending on whether the query returned any results.

const activeFirstSlide = $('.slider.first-slide.active');
if (activeFirstSlide.length) {
  // Found an element
  $('.swiper').css('height', '100vh')
}
else {
  // No active first-slide 
  $('.swiper').css('height', 'auto')
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217