0

I have these html structure here,

<div class="myCaption">
 <h2>caption 1</h2>
 <h2>caption 2</h2>
 <h2>caption 3</h2>
 <h2>caption 4</h2>
 <h2>caption 5</h2>
</div>

I wonder how to use jquery to add a Class "active" to the first H2 tag, and then every e.g, 2 second, switch the "active" class from the first H2 tag to the second H2 tag and then to the third.....when come to the last H2 tag, it will loop again to the first H2, infinitely. Please advise. Thanks.

1
  • If you could provide the javascript youve already attempted to write to do this that would be great. also, just in case you havent attempted it please look at w3schools they have both jquery and javascript tutorials. I thought stackoverflow was about learning not getting free code? Commented Nov 21, 2012 at 4:24

4 Answers 4

5

You'll need to use setInterval to start a timer that processes your changes. Here's a working fiddle

$(function(){ 
    //get all of the h2 tags.
    var h2s = $('.myCaption h2');

    //set up a counter
    var counter = 0;

    //start the interval
    setInterval(function(){

       //remove any active classes you have on the h2s.
       h2s.removeClass('active');

       // update the counter, use a modulo on it with the number of
       // h2 tags to find an index. Get the jquery object at that index, 
       // and add the class to that.
       h2s.eq(counter++ % h2s.length).addClass('active');

    }, 2000); //2000 milliseconds = 2 seconds.
});

Edit: thanks @Christophe, I forgot about eq().

Sign up to request clarification or add additional context in comments.

1 Comment

h2s.eq(current++ % h2s.length) ?
1

You are probably going to want setTimeout inside a while loop. You'll keep an index in a variable, and each iteration you'll remove the active class, increment the index, add the active class to the new index. Rinse, repeat. When your index is the same size as the number of h2 tags, set it to zero.

3 Comments

"setTimeout inside a while loop" - Not inside a while loop: rather you'd use setTimeout() to create an "async loop" instead of using a traditional while or for.
@nnnnnn good point. I was trying to talk it out rather than giving OP copypasta, thus I did not write the code and discover my own error. pete's answer uses setTimeout recursively, which is the route I probably would have taken, and blesh's just uses setInterval, which I missed and is simpler and better for this application.
Yeah, I'm sure if you'd written out the code you'd have done it right. I do agree with you that it's good to just describe the general concept and leave it to the OP to implement it.
1
$(document).ready(function() {
    'use strict';
    var activeCaption = 0,
        switchCaption = function switchCaption() {
            var captions = $('div.myCaption > h2'),
                count = captions.length - 1;
            captions.removeClass('active');
            captions.eq(activeCaption).addClass('active');
            if (activeCaption < count) {
                activeCaption += 1;
            } else {
                activeCaption = 0;
            }
            window.setTimeout(switchCaption, 2000);
        };
    switchCaption();

});​

Working demo: http://jsfiddle.net/NPRzM/

Comments

0
setInterval(function() {
        var current = $('div.myCaption > h2.active'),
            next = current.next().length?current.next():$('div.myCaption > h2').eq(0);
        current.removeClass('active');
        next.addClass('active');
    },2000);

Demo: http://jsfiddle.net/NPRzM/3/

[Update] A slightly more efficient version that caches the selector:

(function(h2s){
setInterval(function() {
    var current = h2s.filter('.active'),
        next = current.next().length?current.next():h2s.eq(0);
    current.removeClass('active');
    next.addClass('active');
},2000);
})($('div.myCaption > h2'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.