Search results

Sample Expand and Collapse Code with Twisting Buttons

by Tom Johnson on Mar 31, 2013
categories: findability

In my previous post, I wrote about how handy collapsing and expanding sections can be. Although there are several plugins that enable this functionality, it's pretty easy to create this functionality yourself from scratch. is a neat site that lets you play around with JavaScript, separating out the HTML, CSS, JavaScript, and result into their own quadrant on the page. I created a "fiddle" showing the HTML, CSS, and JavaScript necessary for the simplest example of a collapsing and expanding section. You can see the end result below or here on its own page. You can also view each section in its own quadrant here. Or embedded here:

Since I plan to work a lot more with JavaScript, I'll probably create a lot more of these fiddles in weeks to come. As a development tool, the fiddle site is neat because it lets you easily adjust styles, HTML, and JavaScript while you're on the same page. It also creates a revision history.

Feel free to use this script or fork it into something better. I added a comment above each line to indicate what's going on. I know there are a lot of similar scripts out there, but many of them are overly complicated. Others don't have the visual expanding or collapsing icons. As far as I can tell, this script is as simple as it can be (just remove the commented lines to shorten it), and it functions the same.

I know there was some discussion about the effectiveness of collapsing sections. In some instances, there are pretty persuasive use cases. For example, if you have an API with various methods that you can run on an object, and you want to list all methods on the same page, collapsing sections will make it easy for users to scan and find the method they're looking for.

About Tom Johnson

Tom Johnson

I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, plain language, tech comm careers, and more. Check out my API documentation course if you're looking for more info about documenting APIs. Or see my posts on AI and AI course section for more on the latest in AI and tech comm.

If you're a technical writer and want to keep on top of the latest trends in the tech comm, be sure to subscribe to email updates below. You can also learn more about me or contact me. Finally, note that the opinions I express on my blog are my own points of view, not that of my employer.