Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html + css + jquery: Toggle Show More/Less Text

I'm working on a personal project and I'm having a small issue:

This is my code code and currently works: http://jsfiddle.net/gvM3b/:

$(".show-more").click(function () {
    $(this).text("(Show Less)");
$(".text").toggleClass("show-more-height");
});​

The issue is that the "(Show More)" text changes to "(Show Less)" but not switches back when needed.

^That's one thing, an additional thing would be if you know how to add the [...] when it says show more but on the text. Been trying to figure it out but had to ask for a little of help, I'm new to jquery.

Thanks!

like image 498
Daniel Avatar asked Aug 08 '26 21:08

Daniel


2 Answers

Update your jQuery:

$(".show-more").click(function () {
    if($(".text").hasClass("show-more-height")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }

    $(".text").toggleClass("show-more-height");
});

See http://jsfiddle.net/gvM3b/1/

like image 92
Gabriel Santos Avatar answered Aug 10 '26 13:08

Gabriel Santos


Use the ternary operator, for example:

$(".show-more").click(function () {
  var $this = $(this);
  $this.text($this.text() == "(Show Less)" ? "(Show More)" : "(Show Less)");
  $(".text").toggleClass("show-more-height");
});​

Or using .text() with a function:

$(".show-more").click(function () {
  $(this).text(function (i, oldText) {            
    return oldText == "(Show Less)" ? "(Show More)" : "(Show Less)";      
  });
  $(".text").toggleClass("show-more-height");
});​

DEMO.

like image 27
João Silva Avatar answered Aug 10 '26 13:08

João Silva



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!