Coco Tan
Coco Tan

Reputation: 57

JQuery - How to check specific class value is on the first child or not after click a button

JQuery - How to check specific class value is on the first child in or not after click a button

I have code like this:

<div class="carousel-item active">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>

On webpage, there is a button. When user click this button, a "active" value will be moved to next child. Like this:

<div class="carousel-item">...</div>
<div class="carousel-item active">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>

I want to write code to check that after click this button, "active" value is placed on the first child (with "carousel-item" value) or not.

$('.button').click(function() {
If(//Check that "active" value is on the first child or not, return true if "active" value is on first child){
//Do something here
}
}

I try to mix of find(), :first-child with my code but it doesn't work.

Thanks in advance.

Upvotes: 0

Views: 54

Answers (2)

Nonameix
Nonameix

Reputation: 11

Simple in jquery:

if( $(".carousel-item").first().hasClass("active") ){
   // do something
}

Upvotes: 1

Rab&#239; Ben Youssef
Rab&#239; Ben Youssef

Reputation: 157

You can create a function to get the active index and another function to move it to the next child like so:

function getActiveIndex(){
  var activeIndex = 0;
  var count = 0;
  $('.carousel-item').each(function(){
    count++;
    if($(this).hasClass('active')){
      activeIndex = count;
    }
  });
  return activeIndex;
}

function moveActiveIndex(){
  var activeIndex = getActiveIndex();
  $('.carousel-item:nth-of-type('+activeIndex+')').removeClass('active');
  activeIndex++;
  $('.carousel-item:nth-of-type('+activeIndex+')').addClass('active');
}
.carousel-item {
  background-color: gray;
  border: 1px solid #ddd;
}

.carousel-item.active {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

<div class="carousel-item active">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>
<div class="carousel-item">...</div>

<button type="button" onclick="moveActiveIndex()">Move Active</button>

Upvotes: 1

Related Questions