I have a list of divs (siblings). On page load, the first div is visibile and the rest hidden. On button click, I need the current visible div to hide and the next one to show. Once the last div is visible, when the button is clicked, it needs to loop back to the first div being visible and hiding the last div. I am not sure what the correct approach is but I have been scratching my head at this for hours! Please help! Code below of what I have so far. The active class will have display: block attached to it in the CSS. The divs are all display: none to begin with.
$('.hp-blurb').first().addClass('active');
$('.red-btn').click(function() {
$('.hp-blurb').removeClass('active');
$('.hp-blurb').next().siblings().addClass('active');
});
Here is my HTML:
<div class="red-btn">
<img src="/red-btn.png" alt="red button" /> <spam class="red-btn-text" >PUSH ME</spam>
</div>
<div class="container">
<div class="hp-blurb">
A gorilla has escaped from the ATLANTA zoo. An ENSEMBLE of zookeepers are trying to find it. In the event the gorilla SHOWS signs of fear it could attack.
</div>
<div class="hp-blurb">
A gorilla has escaped from the ATLANTA zoo. An ENSEMBLE of zookeepers are trying to find it. In the event the gorilla SHOWS signs of fear it could attack.
</div>
<div class="hp-blurb">
A gorilla has escaped from the ATLANTA zoo. An ENSEMBLE of zookeepers are trying to find it. In the event the gorilla SHOWS signs of fear it could attack.
</div>
</div>
I have created a fiddle for your solution: check it out @ https://jsfiddle.net/harshapache/89norsk6/
$('.hp-blurb').first().addClass('active');
var totalHpBlurb = 0;
$('.hp-blurb').each(function(){
totalHpBlurb++;
$(this).attr('data-index',totalHpBlurb);
});
$('.red-btn').click(function() {
var index = $('.hp-blurb.active').attr('data-index');
$('.hp-blurb.active').removeClass('active');
if(index < totalHpBlurb){
index++;
$('.hp-blurb[data-index="'+index+'"]').addClass('active');
}else{
$('.hp-blurb[data-index="1"]').addClass('active');
}
});