Monthly Archive for June, 2009

jQuery: Not as hard as it sounds

For the new blogs page I wanted to put together an accordion-like fea­ture for view­ing the posts to make it feel some­what like a feed reader. I looked at dif­fer­ent javascript libraries for this and chose to go with jQuery, not that oth­ers wouldn’t work, but because I had some lim­ited expe­ri­ence with it.

I started toy­ing around with the slideTog­gle() func­tion, but after a cou­ple hours I had to look around the inter­net for some help. I couldn’t have done it with­out Steve Krueger’s tuto­r­ial. Although I didn’t fol­low it exactly, it helped be over a few hurtles.

Here is the code I ended up with.

jQuery(document).ready(function($){
	$('.story').hide();
	$('.title').click(function(){
	if($(this).is('.active')) {
		$(this).toggleClass('active');
  		$(this).next('.story').slideToggle('fast');
  		return false;
  	} else {
  		$('.story:visible').slideUp('fast');
		$('.title.active').removeClass('active');
		$(this).toggleClass('active');
  		$(this).next('.story').slideToggle();
  		return false;
		}
	});
});

Also, as I was delv­ing deeper into this project, I spent a lot of time around the Word­Press Codex. I found this great func­tion called wp_enqueue_script for load­ing javascript libraries. This is for use in Word­Press plu­g­ins and themes so there is no con­flicts or super­flu­ous code. Pretty neat.

Update — June 29
I edited the page so when open­ing an item it will scroll to the top of your win­dow. So much bet­ter. Some help from Learn­ing jQuery and Marc Gra­ban­ski. I am using the jQuery.ScrollTo plugin.

Here is the updated code:

jQuery(document).ready(function($){
	var scrollTop = jQuery(window).scrollTop();
	$('#content > div.story').hide();
	$('#content > h2.title').click(function() {
		$('#content > h2.title').removeClass('active');
		$(this).addClass('active');
		var $nextDiv = $(this).next();
		var $visibleSiblings = $nextDiv.siblings('div.story:visible');
		if ($visibleSiblings.length ) {
			$visibleSiblings.slideUp('fast', function() {
				$nextDiv.slideToggle('fast');
				jQuery('#content > h2').each(function(i, h2){
				h2top = jQuery(h2).offset().top;
				if (scrollTop  h2').each(function(i, h2){
				h2top = jQuery(h2).offset().top;
				if (scrollTop < h2top) {
					jQuery.scrollTo('.active', 300 );
					return false;
				}
			});
		}
	});
});