CSS class timeline set

I had a question about switching classes using jQuery. In my case, I have 4 hyperlinks in the list. I want the following:

In the initial state, my first hyperlink received the class: "active":

first link active

But after a while I want the "active" class to be removed from hyperlink 1 and added to link2. The same process is also for hyperlinks 3 and 4.

So there is always one hyperlink that gets a black background color: enter image description here

Another requirement is that whenever he reaches the last hyperlink (link 4), he must start again with link 1.

How can i do this? This is what I have so far: https://jsfiddle.net/f6ktje52/1/

HTML

<ul class="tab-slide">
    <li><a href="#">Link 1</a></li>
    <li><a  href="#">Link 2</a></li>
    <li><a  href="#">Link 3</a></li>
    <li><a  href="#">Link 4</a></li>
</ul>

JQuery

$(function() {    
    $('.tab-slide li').first().addClass('active');
    setInterval(function() {                
         $('.tab-slide li').next('li').addClass('active');
    }, 1000);
});
+4
source share
4

:

$(function() {    
    var i = 0;
    var $target = $('.tab-slide li');

    setInterval(function(){
        $target.removeClass('active');
        $target.eq(i).addClass('active');
        if( i == $target.length - 1 ) i = 0;
        else i++;
    }, 1000);
});

jsFiddle

+3

https://jsfiddle.net/f6ktje52/7

JavaScript:

$(function() {
    $('.tab-slide li:nth-of-type(1)').addClass('active');

    var i = 1;
    var amount = $('.tab-slide li').length;

    setInterval(function() {   
        if(i > amount) {
            i = 1;
        }

        $('.tab-slide li').removeClass('active');
        $('.tab-slide li:nth-of-type('+i+')').addClass('active');

        i++;
    }, 1000);
});
+2

Try

$(function() {    
    $('.tab-slide li').first().addClass('active');
    var i = 1;
    setInterval(function(index) { 

         $('.tab-slide li').removeClass('active');
         $('.tab-slide li').eq(i).addClass('active');
         i++;
        if(i === $('.tab-slide li').length){
            i = 0;
        }


    }, 1000);
});

Fiddle

+1

- :

$(function() {    
   var list = $('.tab-slide li');
   var i = 0;

   setInterval(function() { 
      $('.tab-slide li.active').removeClass('active');
      $(list[i]).addClass('active');
      i = i < list.length - 1 ? (i+1) : 0;
   }, 1000);
});
0
source

All Articles