1

I have an array with multiple data, and I'd like to index a div with an incremental value.

var fancyboxInfo = [
'Title1', 'Details1', 'Location1', 
'Title2', 'Details2', 'Location2',
'Title3', 'Details3', 'Location3',
]

$(".fancybox").each(function(index) {
   $(this).attr("title", fancyboxInfo[index]);
});

Using 'each', the following ends up being:

<div class="fancybox" title="Title1"></div>
<div class="fancybox" title="Details1"></div>
<div class="fancybox" title="Location1"></div>

I want to make it index [0], [3], [6] etc. Can this be done using jQuery index?

jsFiddle: http://jsfiddle.net/fNNkx/

4 Answers 4

2
x = 0;
$(".fancybox").each(function() {
   if (x < $(".fancybox").length) {
      $(this).attr("title", fancyboxInfo[x]);
      x += 3;
   }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this Norse. It's the most adaptable one for my needs. Really appreciate it, will accept it as the answer when it lets me.
2
$(".fancybox").each(function(index) {
   if(index % 3 == 0) {
      $(this).attr("title", fancyboxInfo[index]);
   }
});

1 Comment

This will not give the desired result.
2

You can also do

$(".fancybox").each(function(index) {
   $(this).attr("title", fancyboxInfo[(index*3)]);
});

1 Comment

fancy box has 3 elements. The array has 9 elements. The mapping is 0-0, 1-3, 2-6. The index will be 0,1,2. So its index*3 and not index+=3.
1

You can do

var fancyboxInfo = [
    'Title1', 'Details1', 'Location1',
    'Title2', 'Details2', 'Location2',
    'Title3', 'Details3', 'Location3',
    'Title4', 'Details3', 'Location3',        
  ]
i=0;
$(".fancybox").each(function(index) {


      $(this).attr("title", fancyboxInfo[i]);
  i = i+3;
});

1 Comment

I've marked this up, as this also works perfectly (but came after I'd already accepted the answer). Thanks! :)

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.