Nico Plyley
Nico Plyley

Reputation: 102

jQuery Counter add number to class

I'm have a for loop on jQuery and I want my counter to add a class each time with the number of the array it's coming from. But if I write:.addClass("delay"+counter++) that obviously won't work. Would there be another way of going about this.

For example this is what I have so far

            $(document).ready(function() {
                var counter = 1;
                $.getJSON('http://www.passionla.com/app/blog-data.php', function(data) {
                    $.each(data, function(key, value) {
                        $('.blog').append("<div class='post animated slideInRight "+ counter++ +"' style=\"background:url('"+value.header+"') no-repeat; background-size: 100% 100%\"><div class='color'><div class='wrapper'><h1>"+value.title+"</h1></div></div></div>");
                    });
                }); 
            });

Upvotes: 1

Views: 3148

Answers (1)

Derek Story
Derek Story

Reputation: 9593

Its probably easier to increase the counter as a variable and then attach the variable to the class:

JS Fiddle

$('div').each(function(i) {
    var $this = $(this); 
    var newClass = "delay" + i++;
    $this.addClass(newClass);
});

But you would use the .each() function on your returned data instead of div.

Upvotes: 2

Related Questions