Less cats, more code. Let’s roll…
This week I deployed/launched/droppedlikeitwashot a new version of Barista Kid’s Upcoming Events page.
It’s basically a separate blog within our network of WordPress sites. Each day had a single entry with events listed within the post and were scheduled for the day of those events (I have the blog set up to publish future posts). This was totally inefficient, though, and Georgette (the editor-in-chief) wanted something nicer, efficient’er and a little more dynamic’er.
We wanted to have individual posts for each event, and just have the event’s name and date show. When the user clicks the event title, then all extra information and copy would show by sliding down. Here is how it looks all jQuery’d and prettied up:

So there are two important elements to making this work:
1. You need the content to hide. In this case, I’m hiding any output of the_content(). I wrapped that function call with a div of class="event-info".
2. You need the trigger for showing and hiding your content. I want to have the content toggle when the user clicks on the title, which is output with the call of the the_title() function, so I wrapped that in a h3 header of class="event-title".
<h3 class="event-title"> <?php the_title(); ?> </h3> <div class="event-info"> <?php the_content(); ?> </div> |
If you go to the site, you can see that I have a LOT more going on in the loop than just title and post content, but you can get the gist of what’s going on. Anything inside the event-info class will be hidden and clicking on anything inside the event-title class will toggle the visibility of the event-info class.
Of course, nothing is happening now, because we need some jQuery to make it work. And to make this jQuery code work, you need to import the jQuery UI library along with the main one. You can get links to the latest versions on Script SRC. Let’s start with the code:
<script type="text/javascript"> jQuery(document).ready(function($){ $(".event-info").hide(); // make sure all content in event-info class is hidden $(".event-title").click(function(){ // find the .event-info within the same div as .event-title is and slide to show $(this).parent().children(".event-info").toggle("slide", {direction: "up"}, 500); }) }); </script> |
You can do an if/else statement to show content if hidden and vice-versa, but using the toggle function eliminates the need. What that parent/child nonsense does is make sure that we’re only toggling the event-info content that is in the same post as the event-title we are clicking on – otherwise every single post’s content will show when you click on any title. This will cause mayhem with the user experience gods, and myself.
Whenever I teach JavaScript or any language, I like to stress that some really cool things can be done with just a little bit of code. This change to the Events site is a great example, because not much work was needed to transform this blog-like page into a sophisticated events listing.