Throughout the development process of a new website it can be easy to duplicate code that performs the exact same, or very similar functionality time after time. The reasons why aren’t the point of this article, instead here’s one solution to one such piece of functionality where it’s easy to find yourself duplicating code that fundamentally achieves the same goal.

Note: The examples below largely utilises jQuery, however this solution can be converted to vanilla JavaScript.

The Problem

Whether it’s drop down menus or tabbed content, a lot of websites show content that is hidden on initial load when the user clicks on a link or button. Though this can be achieved solely in CSS (more on this later in the article), in most cases JavaScript is often relied upon to add such functionality in a more user friendly and visually appealing way.

Here’s a basic example…

Simple, right? But as soon as we add non-generic class names the likelihood that this can be reused is limited. Not only this but the show() function is a rather basic way of revealing hidden content.

A generic show/hide function

Instead of relying on specific class names or even basic jQuery functions to show content we instead utilise generic data-* attributes as well as CSS animation to ensure smooth transitions.


The JavaScript/jQuery


Progressive Enhancement

As you may also notice, from the CSS, that we include code so that the link will display the hidden element without JavaScript at all. We do so through the use of the :target pseudo class. With so many websites relying on JavaScript and a number of websites displaying only a blank page if JavaScript is disabled or hasn’t loaded it’s important for us that our websites adopt Progressive Enhancement so that basic functionality is available to as many users as possible.

Over to you…

In some cases having a reusable function like this might be overkill. You’re unlikely to need such a function if you’re only likely to use it once or twice, but certainly as you start dealing with larger websites it’s important to try to minimise the amount of code you write and be smart about writing code that works in a wider set of circumstances. Maybe you’ll use our version, or remix it to your specific needs/standards/likes, but in reality we just hope it helps you optimise your JavasScript on future projects.

Add a comment