0

http://jsfiddle.net/fe3hnh4x/

<div class="text">(some text...)</div>

   var text = $(".text").text();
   var excerpt = '';
    if(text.length > 100) {
        console.log(text.length);
         excerpt = text.substr(0, 100);   
         $(".text").html(excerpt + "<div class='readMore'><a href='#'>Read More</a</div>");
    }

    $(".readMore").on('click', function() {
       $(".text").html(text +  "<div class='showLess'><a href='#'>Show Less</a></div>");
    });

    $(".showLess").on('click', function() {
       $(".text").html(excerpt +  "<div class='readMore'><a href='#'>Read More</a></div>");
    });

I am trying to make an excerpt of text using javascript. When the "Read More" is clicked, and whole text and the "Show Less" is displayed. And when the "Show Less" is clicked, the excerpt and "Read More" shows again. The "Show Less" does not trigger any event, but the "Read More" seems to work. Why?

Joshua Leung
  • 2,219
  • 7
  • 29
  • 52

3 Answers3

1

Try this:

   $(document).on('click', ".showLess", function () {
       $(".text").html(excerpt + "<div class='readMore'><a href='#'>Read More</a></div>");
   });

Demo: http://jsfiddle.net/fe3hnh4x/1/

And here is the explanation: Event binding on dynamically created elements?

Community
  • 1
  • 1
K K
  • 17,794
  • 4
  • 30
  • 39
1
   $(".showLess").on('click', function() {

adds the onclick-Handler on every currently existing element of the class 'showLess'

You have to change your readMoreFunction to add the onclick-Handler

$(".readMore").on('click', function() {
   $(".text").html(text +  "<div class='showLess'><a href='#'>Show Less</a></div>");
   $(".text").find(".showLess").on('click', function() { ...

});

HTH Georg

Georg Mavridis
  • 2,312
  • 1
  • 15
  • 23
0

Use event delegation.

$(".text").on('click', '.showLess', function() {});

To be able to catch newly created elements, choose an appropriate container and bind the event to it, then use the second parameter as a filter which you want the event to occur on.

fiddle here

keune
  • 5,779
  • 4
  • 34
  • 50