Expandable sidebar in WordPress with jQuery

This is really simple stuff, you’re wasting your time if you are above the absolute jQuery newbie level.

I keep overwriting my WordPress theme files by working on different computers all the time, sometimes something is lost. It’s time to put down the newest addition in writ so I don’t have to code it over and over again.

Try it out by clicking repeatedly on Show Categories and Show New Posts & Comments, yes we’re using jQuery toggle() here in the head section:

$(document).ready(function(){
  $("#categories_left").hide();
  $("#cat_headline").toggle(
    function(){$("#categories_left").show("slow");}, 
    function(){$("#categories_left").hide("slow");});
  $("#whatsnewwhatsfreshwhatshappening").hide();
  $("#nfh_headline").toggle(
    function(){$("#whatsnewwhatsfreshwhatshappening").show("slow");}, 
    function(){$("#whatsnewwhatsfreshwhatshappening").hide("slow");});
});

So we’re hiding the divs/uls in question to begin with and then simply toggling show/hide when clicks are made, it doesn’t get easier than this. The sidebar HTML:

<ul>
  <li><div id="cat_headline"><h2><a href="#">Show Categories</a></h2></div></li>
  <li>
    <ul id="categories_left">
      <?php wp_list_categories('show_count=1&title_li='); ?>
    </ul>
  </li>
  <li>
    <h2>Most Popular Posts</h2>
     <ul>
     <?php akpc_most_popular(); ?>
     </ul>
  </li>
  <li><div id="nfh_headline"><h2><a href="#">Show New Posts &amp; Comments</a></h2></div></li>
  <li>
    <?php dynamic_sidebar(); ?>
  </li>
</ul>

Note the anchor tag to get the mouse over effects. Also note the use of divs to be able to fetch by id (“#id”), the use of classes would’ve been cleaner with (“.class”), I could throw the divs out then. The problem is that that might change the appearance of the anchors, I would have to go in and look in my CSS to check up on that one and I’m lazy, it’s easier just to add the divs and be done with it.

The dynamic_sidebar() will expand into:

<div id="whatsnewwhatsfreshwhatshappening" style="">
<h2 style="">Latest Posts</h2>
. . .
</div>

That is why the above fetch by $(“#whatsnewwhatsfreshwhatshappening”) works. For more info on What’s New What’s Fresh What’s Happening and the rest feel free to take a look at my WordPress setup.

Related Posts

Tags: , ,