Saturday, January 22, 2011

Blogger: Animated Collapsible Widgets with JQuery

I began experimenting with JQuery this week while working on another project. It is my first experience with the library, having been away from web development until recently. While reading the documentation and experimenting I came across a nice animation effect similar to the function of the Collapsible Widgets script from earlier this week. So, I thought why not take things to the next level and add those animations.

Adding the Script to Your Blog
First things first, let's add the script to the template. Open up Design->Edit HTML then search for the </body> tag. Copy and paste this script just above that </body> tag.

<script src='http://code.jquery.com/jquery-latest.js'/>
<script type='text/javascript'>
//<![CDATA[
function addShowHide(strWidget) {
  var $Widget = $("#" + strWidget),
      $Header = $Widget.children("h2").first();

  if(typeof($Header) != 'undefined')
  {
    var strContWidget = "cont" + strWidget;

    var $Cont = $Widget.children("div").first();
    if($Cont.attr("id") == ""){$Cont.attr("id", strContWidget);}
    else { strContWidget = $Cont.attr("id"); }

    var strASH = '<a href="javascript:doSlide(\'' + strContWidget + '\')"> +/- </a>';
    $Header.prepend(strASH);
  }
}
function doSlide(strCont) {  $('#' + strCont).slideToggle('fast'); }
//]]>
</script>


Making a Widget Collapsible
The script makes the animation possible, but we need to add a command for each widget to collapse. This requires the widget ID found by loading the blog, right clicking the page and viewing source. From there hit Ctrl+F and type in the widget title. For instance search for Blog Archive and you'll find <div class='widget BlogArchive' id='BlogArchive1'> nearby. Copy the ID BlogArchive1, then add this line addShowHide("BlogArchive1"); to the template script just before //]]> at the end. Preview the changes and look for a +/- link just in front of the Blog Archive title. If it's there, Save Template and try out your new smooth collapsible widgets. Perform these same steps for any additional widgets you'd like.

Conclusion
JQuery takes my collapsible widget script to the next level with an elegant animation. It's simple to add and easy to apply to as many widgets as you like. Give it a try for yourself and enjoy.
1 Comments
Comments

1 comments :

Anonymous said...

This code conflicts with other javascripts of my blog including the drop down menu. I believe this can be undone by avoiding the conflict but I am not sure how. Can you please make your code conflict free?

Thanks.

Post a Comment