How to Expand/collapse WordPress posts with jQuery

WordPress has the <!–more->feature which make the post “Condensable” for the main post view page, but sometime that feature doe not fulfill the requirement.

I’d like the user to have the option to expand the post that interests him, while keeping him in the context of all the other post headlines. This is a very popular jQuery enhancement. Let’s take a look at how we’d do that. Set up a clean custom-jquery.js file in your theme and let’s get started.

First, hide the post content:

jQuery(“.post .entry-content”).hide();?

Next, it would be very inefficient to have an editor add a control element to each post. So, we could add it to the theme’s post.php page, but then, the control would appear even if the user had JavaScript disabled. We want this
to degrade gracefully, it’s an enhancement after all.
If someone comes across this content in a mobile browser without JavaScript support or a text-only or text-to-speech browser, we’ll want them to just view the content as normal without any non-functional elements distracting them. We’ll use jQuery to add our control element. If JavaScript is disabled, it simply won’t appear.

jQuery(“.post”).after(“<div class=’openIt’ style=’border-top: 1px solid #666; color: #036; text-align:right; cursor:pointer;’>Expand</div>”);

We now just need a nice way to show and hide the post’s content:
jQuery(“.openIt”).click(function() {
jQuery(this).prev(“.post”).find(“.entry”).slideToggle(“slow”);
});

Last, let’s make sure the instructions in the .openIt div update:

jQuery(“.openIt”).toggle(function(){
jQuery(this).html(“Close”)},
function(){
jQuery(this).html(“Expand”)
});

That’s it! This is very  useful jQuery enhancement for WordPress.

References and More Resources:

Show/Hide any div box with jQuery in WordPress
More Showing, More Hiding
Assorted built-in jQuery show/hide effects
Simple Jquery Show/Hide Div
How to Expand / Collapse Latest Posts or Archives
How to expand collapse (toggle) div layer using jQuery
How to Expand/Collapse TreeCtrl nodes by using Enter Key?
Expanding Text plugin for WordPress
Collapse-O-Matic WordPress Plugin

WordPress 3.0 jQuery: Enhance your WordPress website

About Author

Nur

I am a Wordpress, Website Developer and Designer, creator @ WP Arena, Provide Free WordPress consultation and can help to install WordPress in a secure way to small businesses and bloggers.