perkes456 perkes456 - 6 months ago 17
jQuery Question

Getting current month from array of months

I have an array which basically look like this:

This array is dynamic and lets say it has following months inside:


"May","June"


It can be like this as well:


"May","June","July"...


I need to be able to setup in my slider on the current month. I've been doing this like following:

swiper.slideTo(new DateTime().getMonth()); // fetches current month index ( if May it is 5 since indexation goes from 0)


And my slides looked like this:

<div class="swiper-wrapper">
<div class="swiper-slide active"><h3>January</h3></div>
<div class="swiper-slide active"><h3>February</h3></div>
<div class="swiper-slide active"><h3>March</h3></div>
<div class="swiper-slide active"><h3>April</h3></div>
<div class="swiper-slide active"><h3>May</h3></div>
<div class="swiper-slide active"><h3>June</h3></div>
<div class="swiper-slide active"><h3>July</h3></div>
<div class="swiper-slide active"><h3>August</h3></div>
<div class="swiper-slide active"><h3>September</h3></div>
<div class="swiper-slide active"><h3>October</h3></div>
<div class="swiper-slide active"><h3>November</h3></div>
<div class="swiper-slide active"><h3>December</h3></div>
</div>


And the indexation in the swiper were going from 0 to 11 as well so it was easy to set the current slide to the current month. The problem now is how can I set the current month if the array doesn't starts from January, but that I'm still able to set the current slide to the correct month... Like for example if slides start from May to July... If the current month is June, I'd like to be able to set the current slide to June...

How could I do this?

Answer

This would be really easy using jQuery

var search = "May";

var indexOfCurrentMonthSwiper;

var currentMonthSwiper = $(".swiper-slide").filter(function(i){
    if ($(this).find("h3").html() == search){
      indexOfCurrentMonthSwiper = i;
      return true;
    }
    return false;
});

console.log(currentMonthSwiper, indexOfCurrentMonthSwiper);

JSFiddle

Comments