user1937021
user1937021

Reputation: 10791

Add class to specific element 10 at a time

I'd like to add a class to all .path elements but 10 at a time. I have the following code:

$(".path").each(function(i) {
    var e = $(this);

    setTimeout(function(){
        e.addClass('show');
    }, 100);
});

this adds a class to each element 1 at a time but how could I add 10 at a time.

Upvotes: 2

Views: 90

Answers (3)

Maxi Schvindt
Maxi Schvindt

Reputation: 1462

try this option. I think the user wants to add .show all the elements .path in simultaneous. But now, better explained in the comments.

//$(".path").addClass("show);

New option

var refreshIntervalId = setInterval(function(){
            if($(".path:not(.show)").length == 0) {
            alert("Finish");
                  clearInterval(refreshIntervalId);      
      } else {
          $(".path:not(.show)").slice(0,10).addClass("show");
          console.log("Run");
      }
}, 300);

https://jsfiddle.net/yosrc11u/4/

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You can do it by combining the slice and normal for loop,

var elem = $(".path");
for(i=0;i<elem.length;i+=10) {
 setTimeout(function(i){
   elem.slice(i,i+10).addClass("show")
 }, 100 * i, i);
}

DEMO

Upvotes: 6

gurvinder372
gurvinder372

Reputation: 68393

You can use slice method like this

var first10Elements = $(".path").slice(0,10);
first10Elements.addClass('show');

You can keep a counter counter

var counter = 0;
function addClass()
{
    if ( counter > $(".path").size() )
    {
       return false;
    }
    var first10Elements = $(".path").slice(counter,counter+10);
    first10Elements.addClass('show');
    counter = counter+10;
    setTimeout(function(){
        addClass();
    }, 100);
}
addClass();

This method will add class show to 10 path elements at a time and stop when all of them are done.

And you can generalize it like this

function addClass(currentClass, newClass, counter)
{
    $("." + currentClass ).slice(counter,counter+10).addClass( newClass );
    setTimeout(function(){
        if ( counter < $(".path").size() )
        {
           addClass(currentClass, newClass, counter+10);
        }
    }, 100);
}
addClass("path", "show", 0);

Upvotes: 2

Related Questions