JavaScript issue with FAQ page and read more

Hi i have a FAQ page with many questions. Question have the same class name.
My problem, is i don’t know how to show and hide all the different question content on read more / read less.

I get the first content block to expand on read more. There is no read more on the other blocks. I am still new to javascript

Read More
var s = $("#aboutExpand").html();

if (s.split(' ').length > 50) {
    $("#aboutExpand").html(s.split(' ').slice(0,50).join(' ') + " ... " + '<a href="#" class="read-more">Read more</a>');
}

$("a.read-more").click(function() {
    $("#aboutExpand").html(s);
});

Page content

                        <article>
                            <div class="moreExpandWrapp">
                                <div class="moreExpandContent" id="aboutExpand">
                                <?php the_content(); ?>
                                 </div>
                             </div>
                        </article>

Thanks in advance

New issue:
Thanks, your code work perfectly in jsfiddle. I am currently using WordPress and had to write the code like this. I have a new problem. Sometimes the read more button doesnt work. I think it might be the way i incorporated the code in WordPress.

(function ($) {
$(document).ready(function () {

$(".moreExpandContent").each(function() {
      var s = $(this).html(),
        self = $(this);

      if (s.split(' ').length > 40) {
        self.html(s.split(' ').slice(0, 40).join(' ') + " ... " + '<a href="#" class="read-more">Read more</a>');
        self.children('a.read-more').click(function() {
        self.html(s);
        })
      }
});

});

})(jQuery);

Is this actually the correct way to write it in WordPress?
If not, does any one know the correct way?

Related posts

1 comment

  1. What you need is to target all divs with class ‘.moreExpandContent’ with a jQuery.each call, ids can’t be used for this purpose because they’re supposed to be unique, well this is what you need:

    $(".moreExpandContent").each(function() {
      var s = $(this).html(),
        self = $(this);
      if (s.split(' ').length > 50) {
        self.html(s.split(' ').slice(0, 50).join(' ') + " ... " + '<a href="#" class="read-more">Read more</a>');
        self.children('a.read-more').click(function() {
          self.html(s);
        })
      }
    });

    this is a working jsFiddle demo: https://jsfiddle.net/Le4j3apj/

Comments are closed.