Nenad Vracar
Nenad Vracar

Reputation: 122047

Do something when last item with same class is hidden

Let's say I have few divs with same class .box. When I click on one of these items, I set display: none to that box. Is there a way to find when the last element with the same class (or in this case .box) is being clicked and hidden? For example, when I click and hide the last box, I want to alert something.

Here is https://jsfiddle.net/2Lzo9vfc/139/

I tried something like this but I don't know how to find and trigger this when the last one is clicked.

if ($('.box:visible').length == 0)
{
  alert('No visible boxes');
}

Upvotes: 0

Views: 73

Answers (2)

Melvinr
Melvinr

Reputation: 534

As you are using jQuery you can use index() function to get the last element position, as follows:

$('.box').click(function() {
    var clicked = $(this).index();
    // -1 because index starts in 0 
    var len = $('.box').length - 1;
    if (len == clicked)
    {
        alert('No visible boxes');

    }else{
        $(this).css('display', 'none');
    }

});

Running fiddle: https://jsfiddle.net/2Lzo9vfc/142/

Upvotes: 0

Timothy
Timothy

Reputation: 2003

Try to put your if-statement inside your click action

$('.box').click(function() {
    $(this).css('display', 'none');

    if ($('.box:visible').length == 0)
    {
      alert('No visible boxes');
    }
});

Upvotes: 3

Related Questions