Ciprian
Ciprian

Reputation: 3226

Show hide li elements jQuery

How do I show li elements and then hide them. What I have below hides the list items I don't want to show, it shows all of them when I click the a.show-button link, but I also want to hide the list items by clicking the same link after I change its class. Can't seem to get it to alert Hello. I checked and the classes change. What am I doing wrong?

$('ul.artists li:gt(27)').hide();

$('a.show-button').click(function(e) {
e.preventDefault();
    $('ul.artists li:gt(27)').show();
    $(this).addClass('hide-button').removeClass('show-button');
});

$('a.hide-button').on('click', function(e) {
e.preventDefault();
    alert("Hello");
});

Upvotes: 0

Views: 5368

Answers (2)

ndry
ndry

Reputation: 301

And here is not about how to do it, but about what you are doing wrong.

When you bind an click action to $('a.hide-button'), you bind it to concrete elements. And if new element starts fitting this selector, that element does not automatically get that click action bound.

Upvotes: 0

IndoKnight
IndoKnight

Reputation: 1864

Instead of changing class names to show and hide, try using toggle.

$('ul.artists li:gt(27)').hide();

$('a.buttonClass').click(function(e) {
  e.preventDefault();
  $('ul.artists li:gt(27)').toggle();

});

Upvotes: 2

Related Questions