Cas Cornelissen
Cas Cornelissen

Reputation: 617

jQuery: .is :last-child (or first-child) with specific class

I'm working on a catalog for bicycles which includes filtering and a lightbox for detailed information.

The bicycle overview consists of a large ul with li's in it, where each li represents one bicycle. Detailed information (which is used to filter) is set and read via data attributes. If a li has class .show it matches the filter criteria and is thus shown in the overview.

When navigating the lightbox (prev/next arrows) the user should only see the bicycles that match the criteria (has .show), which is what I've got working.

The last step (which I'm asking this question for) is: in the lightbox I want the 'previous' arrow to disappear when the first bicycle is active and the 'next' arrow should disappear when the last bicycle is active.

I tried this:

if ( info.is(":last-child") ) { 
    lightbox.find(".lightbox-nav-next").hide();
} else { 
    lightbox.find(".lightbox-nav-next").show();
};

Where info is the li that is being shown in the lightbox at that moment.

I'm wondering why info.is(":last-child") is not working... I think it is because it selects the last child without considering if it has class .show.

What is the best way to solve this? Thanks in advance!

EDIT: The page I'm talking about is online at: http://dev.onefinitystudios.com/rvs/verkoop.html. The file where the javascript is located is catalogus.js.

Upvotes: 0

Views: 2331

Answers (4)

Tomalak
Tomalak

Reputation: 338148

lightbox.find(".lightbox-nav-next").toggle(function () {
  return ! info.is(".show:last");
});

and

lightbox.find(".lightbox-nav-prev").toggle(function () {
  return ! info.is(".show:first");
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the :last selector.

What you need to check is whether info is same as the last item with class show, it can be achieved with $('.show:last').is(info).

if ( $('.show:last').is(info) ) { 
    lightbox.find(".lightbox-nav-next").hide();
} else { 
    lightbox.find(".lightbox-nav-next").show();
}

Upvotes: 3

techfoobar
techfoobar

Reputation: 66663

Try instead with :last (yes, its not from CSS, but a jQuery addition)

i.e.

if ( info.is(":last") ) { 
   ...

Docs

Upvotes: 0

Andrew
Andrew

Reputation: 1880

You can also use jquery .last()

jquery .last() selects the last child anyway

So your code would be something like:

if ( info.last() ) { 
    lightbox.find(".lightbox-nav-next").hide();
} else { 
    lightbox.find(".lightbox-nav-next").show();
};

http://api.jquery.com/last/

Upvotes: 0

Related Questions