How to show and hide divs with headlines using JQuery

I finally updated my academic website after, like, a year. One thing that I had been meaning to do was make little drop-down things for the projects/topics I’m working on or interested in. It’s pretty straightforward with JQuery, but I couldn’t find a ready-made solution for what I wanted to do, so I figured it might be useful to post it here.

What I wanted to do was to have a title for each little section, which could be clicked to expand or collapse that individual section. The most obvious solution is to toggle the visibility of each section’s div every time it’s clicked on, but I didn’t want to futz with fancy CSS to make the headline for each section remain when the rest was hidden. Instead, I just toggle the visibility of the siblings of the headline instead, which is everything else contained in the same section as the headline.

Here is the Javascript:

$(document).ready(function() {
    $(".sliding > h3.slidingtitle").click(function() {
    $(".sliding > h3.slidingtitle").siblings().hide();

The “.sliding > h3.slidingtitle” selector identifies the h3 elements that have class “slidingtitle” and live inside something with class “sliding” (that last part probably not strictly necessary). Here’s what each section’s HTML looks like:

<div class="sliding">
    <h3 class="slidingtitle">Headline goes here</h3>
    <p>Content goes here</p>
    <p>...yet more content</p>

That was easy, eh? JQuery sure is nice.


    Leave a Reply

    Fill in your details below or click an icon to log in: Logo

    You are commenting using your account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

%d bloggers like this: