user1817708
user1817708

Reputation: 45

jQuery addClass removeClass with timer

I have an issue with a 'Latest News' module. Please have a look at http://www.proudfootsupermarkets.com/ to see an example of the module (it's the div close to the top of the page which has a large image in it).

At the moment I have it set up so that when a user clicks on a tab the main article shows. The jQuery for this is:

    jQuery(document).ready(function() {

    $(".moduletable.latestnews article:first-child").addClass("atfront")

    $(".moduletable.latestnews article").click(function(){
        $(".moduletable.latestnews article").css("zIndex",1).addClass("atback").removeClass("atfront");
        $(this).css("zIndex",100).addClass("atfront").removeClass("atback");
    });
});

This is all quite simple and straight forward. The problem that I am having is that I want the articles to change automatically after a few seconds. This would then go in an infinite loop starting with article 1 and then after a couple of seconds showing article 2 etc etc...

I am sure that this is fairly simple but I have just about exhausted my knowledge of JavaScript. Thank you for any help that you are able to give :)

I have created a jsfiddle http://jsfiddle.net/Bempv/

Upvotes: 1

Views: 1522

Answers (1)

Rune FS
Rune FS

Reputation: 21742

You can use setTimeout to change the article in front. If you select the article with the class ".atfront" and then use the .next() selector you should get the functionality you are looking for

$(function(){
    var articleToggler = function articleToggler(){
    var front = "atfront",
        back = "atback";
    return function(){
       var selection = $(".moduletable.latestnews")
                          .find("article.atfront")
                          .addClass(back)
                          .removeClass(front);
           next = selection.next("article"); 
           next = next.length ? next : $(".moduletable.latestnews")
                                   .find("article").first();
           next.addClass(front)
               .removeClass(back);
           console.log(selection.length,next[0])  


       setTimeout(articleToggler(),1000); //changes every second
    };
};

//start the rotation
(articleToggler())();
});

The setTimeout will call the function passed as the first argument once the timeout expires. The timeout argument is in miliseconds so the above code wait for 1 second before calling the function. Since the above function adds it self as the callback this will repeat indefinately

Upvotes: 2

Related Questions