Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show more button

I want to show LIs which have "hidden"class when I click on button.

$(".show-more a").on("click", function() {
    if(linkText === "SHOW MORE"){
        linkText = "Show less";
        $('.hidden').css('visible', 'visible');
        $('.hidden').css('display', 'block');
    } else {
        linkText = "Show more";
        $('.hidden').css('visible', 'hidden');
        $('.hidden').css('display', 'none');
    };

    $this.text(linkText);
});
.hidden {
display: none;
visibility: hidden;
}
<ul>
  <li>Lorem</li>
  <li>Lorem</li>
  <li class="hidden">Ipsum</li>
</ul>
<div class="show-more">
  <a href="#">Show more</a>
</div>

I think that my Javascript is absolutely wrong, I am beginner. Help me Thanks


1 Answers

You are performing a strict comparison === so the letter case is important.

if(linkText === "Show more"){

How about removing the class that hides those elements?

$(".show-more a").on("click", function() {
    if(linkText === "Show more"){
        linkText = "Show less";
        $('li.hidden').removeClass('hidden')
    } else {
        linkText = "Show more";
        $('li.hidden').addClass('hidden')
    };

    $this.text(linkText);
});

jsFiddle with some additional refactors: https://jsfiddle.net/rt0cs8jh/

like image 98
Unamata Sanatarai Avatar answered Apr 22 '26 20:04

Unamata Sanatarai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!