Expandable / Collapsible Text using jQuery

I’d like to first talk about my relationship with Javascript before I get into jQuery. I’ve known Javascript since the 90s, back when I was a young lad, Javascript freaked me out – I’ll admit I was really intimidated by Javascript more than I was with PHP. I mean they even have a modern looking official site for Javascript now that’s not so daunting.

Fast forward to now… my relationship with Javascript remains, yes it has been a super rocky one and at times we both thought it was definitely over but Javascript is the type that just doesn’t go away even if you tried to run from it. Yeah I think you know what I’m talking about. And then Javascript gives birth to jQuery – look I don’t care what people say about jQuery and how its being quickly replaced by the new kids on the block – Angular, ReactJS, VueJS and frends, jQuery is a power house and it’s a lot friendlier to work with. I mean, Twitter Bootstrap needs jQuery and whoa who knows how many sites are being powered by Twitter Bootstrap due to its responsive toolpack. I use it on all my pet projects.

So I’ve really grown with Javascript and jQuery, I think I’ve intentionally have taken a slower pace with learning the language simply because of how enjoyable the journey really is. Javascript is a bit more tame than it was once – it’s the ecosystem that’s gone wild so with that thought I really do appreciate Javascript for being around.

Ok enough with the intro. I’m going to dive in the reason for this post. Often times I would get a request for this capability – expandable/collapsible text using jQuery, it’s useful for SEO especially if you have a lot of content you would like to display above the fold. The higher up the content is, not only is it optimal for the visitor but it helps Google crawl important keywords on your page much faster. So hey, I’m all about it.

So if you have something like this…

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pellentesque, ex quis fringilla tincidunt, mauris magna iaculis velit, eget lacinia arcu magna at felis. Fusce commodo mattis quam. Suspendisse eget arcu a neque sagittis elementum nec in diam. Nam ullamcorper diam auctor eros dignissim ullamcorper nec nec nisi. Praesent pellentesque est id semper egestas. Pellentesque sed auctor nibh, quis sodales eros. In hac habitasse platea dictumst. Nulla a ultrices lacus. Sed egestas justo sed dui mollis, ut imperdiet velit dapibus. Nulla sit amet purus sed nunc hendrerit fermentum et vitae arcu. Praesent id ex eu quam vehicula vehicula placerat at dolor. Nulla erat ante, euismod id sapien non, imperdiet cursus eros. Donec tincidunt, enim vel condimentum interdum, velit leo accumsan velit, ut blandit turpis ipsum nec augue. Etiam egestas non erat eget molestie.

Quisque est sapien, ultricies ut rutrum sodales, cursus posuere sem. Integer rutrum arcu a nunc suscipit, non interdum ex tempor. Nullam justo massa, suscipit at tempor quis, rhoncus quis lacus. Nullam eu lectus tristique arcu fringilla iaculis. Quisque in lectus eget enim condimentum lobortis. Nullam condimentum hendrerit nulla vel tincidunt. Integer non aliquet nisi. Nullam facilisis orci quis urna molestie porttitor.</p>

You can hide a portion of it – let’s say a portion of the first paragraph and the second paragraph entirely.


<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pellentesque, ex quis fringilla tincidunt, mauris magna iaculis velit, eget lacinia arcu magna at felis. Fusce commodo mattis quam. Suspendisse eget arcu a neque sagittis elementum nec in diam. Nam ullamcorper diam auctor eros dignissim ullamcorper nec nec nisi.  <span class="toggleThis">Read More</span></p>

<div class="expandThis">
Praesent pellentesque est id semper egestas. Pellentesque sed auctor nibh, quis sodales eros. In hac habitasse platea dictumst. Nulla a ultrices lacus. Sed egestas justo sed dui mollis, ut imperdiet velit dapibus. Nulla sit amet purus sed nunc hendrerit fermentum et vitae arcu. Praesent id ex eu quam vehicula vehicula placerat at dolor. Nulla erat ante, euismod id sapien non, imperdiet cursus eros. Donec tincidunt, enim vel condimentum interdum, velit leo accumsan velit, ut blandit turpis ipsum nec augue. Etiam egestas non erat eget molestie.

Quisque est sapien, ultricies ut rutrum sodales, cursus posuere sem. Integer rutrum arcu a nunc suscipit, non interdum ex tempor. Nullam justo massa, suscipit at tempor quis, rhoncus quis lacus. Nullam eu lectus tristique arcu fringilla iaculis. Quisque in lectus eget enim condimentum lobortis. Nullam condimentum hendrerit nulla vel tincidunt. Integer non aliquet nisi. Nullam facilisis orci quis urna molestie porttitor.</p>
</div>

And below the snippet of code to make it all happen. Let’s break it down.

  • Attach a click() event handler onto the .toggleThis element and listen for the click event
  • Wrap the content you would like to hide with the .expandThis element and style it to display: none
  • Attach the slideToggle event handler to the .expandThis element to give it a nice toggling effect, thank you jQuery.
  • Add a conditional and pseudo class :visible to keep track of the content’s state. I’m a big fan of minimalism so here we we can indicate a “Read More” or “Read Less” feedback switch instead of adding images (plus or minus), entirely up to you. I prefer traveling light and portability.

<script>
$(document).ready(function() {

  $('.toggleThis').click(function() {
    var link = $(this);

    $('.expandThis').slideToggle('slow', function() {

      if ($(this).is(":visible")) {

        link.text('Read Less');

      } else {

        link.text('Read More');

      }

    });

  });

});

</script>

If you’re looking to get it on with Javascript and jQuery, don’t be intimidated. Well, you will be I’m not going to lie. But hang in there, roll with the punches, its a long term developing relationship. It can get rough but you’ll find this duo to get you out of some really tricky situations.