Aaron
Aaron

Reputation: 2500

jQuery/JavaScript Setting Up Array by Attribute

I'm trying out my first lightbox plugin and trying to figure out how to deal with setting up the navigation controls. I know it has to be a simple fix, but I'm totally overthinking this. It supports html content and images and is using the standard rel attribute for gallery connection. My question is: how do I navigate from 1 image (or div) to the next, based on the rel?

At first I though $(this).nextAll('[rel="ExampleGallery"]') would work, but unfortunately this doesn't target the next one. So... I might be completely off track, but what I'm trying to do now if loop through the objects that call the plugin, detect if they have a rel tag, then if they do push their values into dynamically created arrays with the Gallery Names as the array names. Then just use the indexes in the array to navigate through objects...

HTML

<img src="images/pic1.png" width="230px" height="215px" rel="Gallery1"/>
<img src="images/pic2.png" width="230px" height="215px" rel="Gallery2"/>
<img src="images/pic3.png" width="230px" height="215px" rel="Gallery1"/>

ARRAY

Gallery1                  Gallery2

0 (ref to img tag 1)      0 (ref to img tag 2)
1 (ref to img tag 3)

Again, I think I'm doing this wrong, and sorry if this is WAY off. How would I go about writing the JS for this?

1- Dynamically create array based on rel name 2- Push object to array in order to reference later

Thanks so much!

Upvotes: 0

Views: 272

Answers (1)

nbrooks
nbrooks

Reputation: 18233

I think you should rethink the data-structure you want to use for this. However to simply collect the images, this will work:

var arrays = {};
$('img').each(function(){
    var arrayName = $(this).attr('rel');
    if(arrays.hasOwnProperty(arrayName)) {
        arrays[arrayName].push(this);
    }
    else {
        arrays[arrayName] = [this];
    }
}

At the end: arrays is { Gallery1: [img1, img3], Gallery2: [img2] }

Upvotes: 2

Related Questions