Expand Collapse toggle button.

April 14, 2016

I really really enjoy bootstrap. I use it constantly at work and it solves a lot of problems that Front-End Dev’s have had for a while. Probably the biggest one is its grid system, but it’s also got build in JavaScript components. I recently used Collapse.js to create an expand/collapse functionality so the user can view the entire news article or just the teaser.

You can find more about Collapse.js here

It needs a few important things to work.

  1. A container of what you want to show hide and that container must have an ID. In my case it was id="article-1-expanded"
  2. Set the class of that container to class=”collapse”
  3. A Button that toggles the show/hide functionality that must have.

    • data-toggle=”collapse”
    • data-target=”Must match ID in step 1"

    {% codeblock html %}

  4. This Is a News Article

    Wednesday, March 16, 2016 | By Franklyn Roth

    ua. Ut enim ad minim veniam, quis nostrud exercitation ullamco quis nostrud.

    et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.

  5. {% endcodeblock %}

In the CSS I am switching the content to display + Expand/- Collapse with: CSS Code of content: '+Expand'
It could probably have been done with JavaScript/jQuery, but CSS makes it easy with a one liner and that lets you leverage Collapse.js which is already written for you by the smart people at Bootstrap.

Naming the class took me a while. I eventually settled on btn-toggle because...

  1. It’s a button at the end of the day.
  2. Its main purpose is to toggle and it can be added to the Buttons.less file as a modifier.

Bonus: Add in <span class=”sr-only”>Expand to full article</span> so that a user with a screen reader knows what the functionality of the button is. The entire code and working example can be viewed at the codepen below.

See the Pen wGyVQQ by Franklyn (@franklynroth) on CodePen.