HomeProgrammingUsing Dojo for a simple show/hide toggle effect.

Using Dojo for a simple show/hide toggle effect.

Without a doubt, my favorite Javascript library is Dojo Toolkit. Unfortunately, it can be a bit challenging to learn via the dojo.manual, especially if you aren’t interested in the widgets, just the DOM, UI, and FX libraries. I just wrapped up a project where I used Dojo quite heavily on the site. One effect I thought was particularly effective was a simple show/hide toggle with nice fades. Take a look at the live page. It is a simple page, and the code that produces is it is simple, easily understood, and quite cross-browser friendly. Note particularly that I did not use any inline javascript.

How I implemented the effect

Markup First, I made a div section which would be toggled, giving it the id of “suggestions”. Also, I made a graphical button and gave it the id “hider”. Lastly, I made another matching button with the “toggle back on” text. Code Then, I activated the toggle with this code:

dojo.require("dojo.lfx.*");

// show/hide toggle the "suggestions" div
function toggleSuggestions() {
   var suggestion = dojo.byId("suggestions");
   var hider = dojo.byId("hider");

   var display = suggestion.getAttribute('displayed');

   if (display == 'on') {
     dojo.lfx.toggle.fade.hide(suggestion, 1000);
     // change the button image
     hider.setAttribute("src","media/images/show-suggestion.gif");
     display = 'off';
   } else {
     dojo.lfx.toggle.fade.show(suggestion, 1000);
     // change the button image back
     hider.setAttribute("src","media/images/hide-suggestion.gif");
     display = 'on';
   }
   // remember the toggle state
   suggestion.setAttribute('displayed', display);
}

// dom hook and setup
function serenityInit() {
   var hider = dojo.byId('hider');
   // wire the event without using inline javascript, sweet!
   dojo.event.connect(hider,'onclick',toggleSuggestions);
   var suggestion = dojo.byId("suggestions");

   // set the default displayed state
   suggestion.setAttribute('displayed', 'on');
}

// Add the init to the load chain for the page.
dojo.addOnLoad(serenityInit);
FOLLOW US ON:

I started out going to college for Business administration but soon found out that Coding would be a great way to have a sustainable career! I made coder's eye as my personal journey on learning how to code and sharing my Findings along the way. My vision with CE now is to be a way to help beginners that want to learn code but don't know where to start.

NO COMMENTS

Sorry, the comment form is closed at this time.