user3553851
user3553851

Reputation: 71

addClass jquery loop

I'm working on a web project that has a changing background image every few seconds. Problem is I don't know how to get the first image to return after all images are finished rotating. After the third image the screen goes white.

html :

<section class="slideshow">
    <img src="img/img1.png" class="bgM show"/>
    <img src="img/img2.png" class="bgM"/>
    <img src="img/img3.jpg" class="bgM"/>                   
</section>

javascript

function switch() {
    var $active = $('.slideshow IMG.show');
    var $next = $active.next(); 
    var $images = new Array(); 
    var $length = $images.length;

    $next.addClass('show');

    $active.removeClass('show');

    if ($images[$length].hasClass('show')) {
        $images[0].addClass('show');
    }
}

$(function() {
    setInterval( "switch()", 8000 );
});

Upvotes: 1

Views: 2108

Answers (2)

Travis J
Travis J

Reputation: 82287

jsFiddle Demo

No need for the extra code. Just use an iterator with mod for the set of image elements.

$(function() {
 var slide = $(".slideshow"), cur = 0;
 setInterval(function(){
  $('.show',slide).removeClass('show');
  $('img',slide).eq((++cur)%3).addClass('show');
 }, 1000 );//using 1000 just for demo purposes
});
.slideshow img.show{
    border:2px solid red;
    display:block;
}
.slideshow img{
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="slideshow">
            <img src="http://placehold.it/350x150" class="bgM show"/>
            <img src="http://placehold.it/250x150" class="bgM"/>
            <img src="http://placehold.it/150x150" class="bgM"/>                   
</section>

Upvotes: 1

Samuel Cook
Samuel Cook

Reputation: 16828

The first major issue is that your function switch is a reserved word (ie choose another name [I chose switch_images]).

Next you can check to see if the "next" image exists (.length). If it doesn't then set it to the first image in the slideshow:

<section class="slideshow">
    <img src="img/img1.png" class="bgM show"/>
    <img src="img/img2.png" class="bgM"/>
    <img src="img/img3.jpg" class="bgM"/>                   
</section>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function switch_images() {
    var $active = $('.slideshow IMG.show');
    var $next = $active.next();

    if(!$next.length){
        $next = $('.slideshow IMG:first');
    }

    $active.removeClass('show');
    $next.addClass('show');
}

$(function() {
    setInterval( "switch_images()", 8000 );
});
</script>

Upvotes: 1

Related Questions