Brendon Dugan
Brendon Dugan

Reputation: 2168

Using JQuery to perform a function on elements with unique rel attribute

I am attempting to improve the portability of a bit of code by automatically detecting what values populate the "rel" attribute of a set of links so that I can create multiple image lightboxes on a page. Basically, right now I am pulling data about hotels from a database, and for each hotel I find I am creating a simple image gallery that consists of a JCarousel, and for each JCarousel the images are able to be clicked launching a lightbox containing only images from that set. Here is the code I currently use to accomplish my goal right now:

$(document).ready(function(){
    $(".carousel").jcarousel({
        wrap: 'circular',
        visible: 3,
        scroll: 1
    });
    $('a.lightbox[rel=9]').lightBox();
    $('a.lightbox[rel=10]').lightBox();
    $('a.lightbox[rel=11]').lightBox();
    $('a.lightbox[rel=13]').lightBox();
});

The problem with the current approach is that if someone else adds a hotel to the database (which will always be the case) the images will appear within the carousel, but will not have the lightbox effect unless I manually add it. This means a fairly significant amount of upkeep if I plan on using this code across multiple websites (which I do).

What I would like to be able to do is detect the unique "rel" attributes for a.lightbox elements, and loop through them in a $.each to apply the lightbox effect. I'm just not sure how to do that. Any advice?

Upvotes: 2

Views: 355

Answers (2)

Alnitak
Alnitak

Reputation: 339836

Use an Object as a kind of associative array to store the seen rel attributes:

var rels = {};  // empty object

$('[rel]').each(function() {     // for every element with a 'rel' attribute
    var r = $(this).attr('rel'); // extract the attribute's value
    rels[r] = 1;                 // store a dummy value in the object
});

rels = Object.keys(rels);        // convert the object to an array of its keys

Then you can apply your lightbox to each unique rel value in turn:

$.each(rels, function(index, value) {
    $('.lightbox[rel="' + value + '"]').lightBox();
});

NB: Object.keys is an ES5 function. See the Mozilla Developer Network site for a compatibility function.

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

You can try this

var $this, rel, rels [9, 10, 11, 13];
$('a.lightbox').each(function(){
   $this = $(this);
   rel = $this.attr("rel");
   if($.inArray(rel , rels) > -1)
     $this.lightBox();
});

Upvotes: 0

Related Questions