In this video, we’ll walk through creating a simple content accordion. All of the sample content for the demo comes from Wikipedia.
Since we’ll be using a lot of special characters, we have to pay special attention to our charset meta tag to make sure all those special characters show up as expected rather than looking look a bunch of gobbledygook.
There are lots of different bits of HTML markup that can be used to create the HTML markup for an accordion, but I like to use a definition list (
<dl>). I use the
<dt> tags for the accordion titles and the
<dd> tags for the accordion content areas. The
<dd> tag can contain any other tags so the content can be quite complex, including headings, paragraphs, lists, images, videos, etc.
In this case, I’m making use of the new HTML
<figcaption> elements for presenting the photos and captions for each city. For the image captions, I’m using the captions provided by Wikipedia to ensure that the photographers are correctly credited for the use of their images.
Once we’ve got all of our content on the page, we’ll style that up with a bit of CSS to make it look like an accordion. After removing some of the browser’s default styles, we add a background color and some rounded corners to the titles and a border around the content areas.
<dd> tags to fold them out of the way. Then, we add a click handler to the
<dt> tags that moves to the next
<dd> tag and shows it when the
<dt> is clicked.
That’s a bit of progress, but we have to add a bit more finesse to get it working like an accordion, like closing any other open panels when we click to open a new one. We make use some of the DOM traversal methods we used last time –
siblings(). We also make use of some of jQuery’s built-in animations –
slideToggle() – which we’ll be covering in detail in next week’s video.
<dt>‘s look and work a little more like buttons, and we add a class to the
<dt> when they’re open so that the open panel can be styled a bit differently from the panels that are closed.
We’ll wrap up by making a few little optimizations – we toggle the ‘+’ and ‘-‘ characters to show if the panel is opened or closed, and style the
<dd> content areas to match the orange color of the open titles. And we learn how to use a CSS3 transition to animate a background color change.