Erik Berger
Erik Berger

Reputation: 609

jQuery .each loop - first element has different class than everything else

I'm trying to create a Flickr slideshow from the API where the first image is only shown and when it is clicked it launches the rest of the gallery in colorbox (lightbox plugin).

Here is my code:

var url = "http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=f0b84fba1c00631410b85b90720f52ba&photoset_id=72157632271202012";
var classes = ['show', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide', 'hide'];
var src;
    $.getJSON(url + "&format=json&jsoncallback=?", function (data) {
        $.each(data.photoset.photo, function (i, item) {
            src = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + ".jpg";
            title = item.title;     

            $(document).ready(function () {
                $("<a>").attr({
                    "href": src,
                    "class": "gallery",
                    "title": title
                }).html(
                    $("<img />").attr({
                        "src": src,
                        "alt": title,
                "class": (classes[i]), //line in question
                        "width": "240",
                        "height": "180"
                    })

                ).appendTo("#thumb");


            });

        });


    });

    $(window).load(function () {
        $(".gallery").colorbox({
            rel: 'group1'
        });
    });

This works nicely except that the way I'm adding the "show" class to the first image and "hide" to the rest is really clunky with the long classes array. Also, as the flickr photoset grows this won't work anymore as it runs out of hide(s) in the array.

There has to be a better way to do this that maybe involves an if else statement that just says the first image gets "show" class and all others get the "hide" class.

Thanks!

Upvotes: 0

Views: 859

Answers (1)

nnnnnn
nnnnnn

Reputation: 150030

Try this:

"class": (i===0 ? "show" : "hide"), //line in question

The conditional operator ? : (also known as the ternary operator) gives you the if/else behaviour you mentioned in the question but inline directly where you need the value.

Note that you don't actually need the parentheses - the following is fine:

"class": i===0 ? "show" : "hide",

...but to my eye it is a little bit clearer with parentheses.

Upvotes: 1

Related Questions