7

How can I get the index of a CoffeeScript .each loop? I've searched everywhere and can't seem to find a solid answer. I know how I can do this with vanilla jQuery, but I can't figure out how to add the index argument to function() in CoffeeScript.

here is my code currently:

video_list_element = $('#video-list li')

video_list_element.each ->
    video_list_element.delay(100).animate({
        "top": "0"
}, 2000)

I'm trying to multiply the value inside of .delay() by the index of the .each loop

Thank you so much for your help, I really appreciate it!!!

Regards, Tim

1 Answer 1

7

Documentation for the jQuery .each() function is found here: http://api.jquery.com/each/

video_list_element = $('#video-list li')
video_list_element.each (index, element) ->
  element.delay(100 * index).animate "top": "0", 2000

In general (sans-jQuery), the way to get the index in a coffeescript for loop is:

array = ["item1", "item2", "item3"]
for value, index in array
  console.log index, value

Gives:

0 item1
1 item2
2 item3
Sign up to request clarification or add additional context in comments.

3 Comments

How can I do this if I want to loop through all the, for example, "p" tags with the selector $('p') and animate each "p" tag using the index to multiply the speed each iteration?
I think you meant to say for value, index in array; of is for looping over object properties, in is for arrays.
Either will work - of will require index, value and in will require value, index. So they do the same thing with the parameters reversed. Regardless, I updated the answer.

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.