Jump to content
Larry Ullman's Book Forums

Javascript Accordion


Recommended Posts

I need to create an accordion style page using Javascript for a site I'm currently working on. I found an example online that I think is going to work great for me. Unfortunately, I do think there may be a few issues with the scripts used. First there is no onload command and I think there should be. Second, I think the global namespace is going to be polluted with variables. I tried wrapping the one of the scripts in an anonymous function but that broke it. I'm not sure how to correct the issues. Any advice would be greatly appreciated. The example page is here:

http://multimediadesignersite.com/test_accordion.html

 

Thanks!

Link to comment
Share on other sites

The problem with everything expanding when the page is first loaded is pretty much unavoidable because that's how the accordion is designed. It's not a browser issue.

Unfortunately, for the accordian to work, it needs to know the max heights of all the divs that will "accordion", and the only way to do that is to, when the page first loads, expand everything, get the necessary measurements, and then close all the divs real quick (hopefully before the user notices).

 

There are some ways to get around this behavior, but they're tricky and depend on your particular implementation. In short, I wouldn't worry about it too much. I think that behavior happens for all these accordion JS libraries, so you're not alone. Everyone has pretty much just learned to live with it.

 

As for polluting the global namespace, if you put everything within an anonymous self-executing function, then you can set up the events within that function, and then everything will work and you will have avoided polluting the global namespace.

 

To be honest though, if you're the end developer, and no one else is going to import your code for something else, then it's not the end of the world to dirty up the global namespace a bit.

 

Nevertheless, if you want to keep things as clean as possible, please do something like the following:

 

(function () {

 var init;

 init = function () {

   // Start code here.

 };

 window.onload = init;

}());

 

Please let us know if you have any other questions.

Thanks.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...