jQuery – making scrolling and toggling simple

I recently discovered jQuery and I thought it looked great. I could hardly wait to try it out in a project and the time has finally come.


In this case we have a list of feeds with the following requirements:

1.) When a link next to the title of each item is pressed we want to display item description (they are hidden by default).

2.) To improve the user experience we want an animation to bring the displayed item description to the middle of the window.

3.) When a user presses the above link again we will hide the item description, however this time we don’t want the animation. It makes no sense enhancing focus on something the user wants to get rid of.

This is how the requirements can be solved with jQuery:

First the markup (rendered with Smarty):

<script language="JavaScript" src="{$baseUrl}/js/jquery.js"></script>
<script language="JavaScript" src="{$baseUrl}/js/jquery.dimensions.js"></script>
<script language="JavaScript" src="{$baseUrl}/js/jquery.scrollTo.js"></script>
<script language="JavaScript" src="{$baseUrl}/js/jquery_help.js"></script>
<table>
{foreach from=$feeds item=feed}
<tr style="background:{cycle values="#ddd,#eee"};">
	<td class="feed_list"><b>{$feed.feedname}</b></td>
	<td class="feed_list" width="700px">
		<a href="{$feed.link}" class="black_link">{$feed.title}</a> <a href="javascript:toggleViz('{$feed.id}')">more</a>
		<div id="{$feed.id}" class="hidden_simple">{$feed.description}</div>
	</td>
	<td class="feed_list"><b>{$feed.category}</b></td>
</tr>
{/foreach}
</table>

Notice that I use the dimensions plugin and the scrollTo plugin. ScrollTo is used to scroll the main window and dimensions are used to read the position of elements in my case. It can be used for a hell of a lot more though.

Let’s take a look at hidden_simple as it is of some importance in our case:

.hidden_simple{
	visibility:hidden;
	width:0px;
	height:0px;
  }
  
  .feed_list{
	margin:0px 0px 0px 0px;
	padding:0px 5px 0px 5px;
  }

So it will hide everything and make it have no size. Let’s move on to the magic. In jquery_help.js I only have the function toggleViz which is called when pressing the more link:

function toggleViz(el_id){
	$("#"+el_id).toggleClass("hidden_simple");
	if($("#"+el_id).attr("className") != "hidden_simple"){
		var scroll_to = $("#"+el_id).position();
		$.scrollTo(scroll_to.top, {speed:500});
	}
}

ToggleClass will apply or remove the hidden_simple class from the element. Next we check if the class in fact is applied, if it is not (if it was just removed which will show the element) we will scroll to the vertical position of the element.

So as you can see, jQuery and Co will make effects ridiculously simple. Javascript is not my strength but libraries like this makes my life extremely easy.


Related Posts

Tags: , , ,