1

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>");
                    });
                }); 
            });
7
  • 1
    It wouldn't work but regardless .addClass typo* Commented Sep 11, 2015 at 3:16
  • 1
    Please add more code Commented Sep 11, 2015 at 3:16
  • Make a codepen/jsfiddle of what you have tried at least Commented Sep 11, 2015 at 3:17
  • what do you mean by won't work.... Commented Sep 11, 2015 at 3:17
  • try .addClass("delay"+ ( counter++ ) ) Commented Sep 11, 2015 at 3:19

1 Answer 1

2

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.

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

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.