views:

82

answers:

1

Hello, hopefully someone can help. I am trying to fiddle with Prototype JS and have a question about a basic collapsible nav structure I am trying to build.

The following works well except for one thing. I would like for the JS to identify if the child or 'next' DOM element is empty to not fire.

The code is:

Event.observe(document, 'dom:loaded', function() {  
 $$('#leftnav li a').each(function(element) {  
  Event.observe(element, 'click', function(event){ 
  Event.stop(event);
  Event.element(event).next(0).toggle(); 
  Event.element(event).up(0).toggleClassName('active');
  }, 
  false);             
 });  
});

So if there not a nested 'UL', don't fire. When I try to break this out into an if else, it seems to fail no matter what.

Thoughts or suggestions?

Thanks!

+1  A: 

Assuming that your HTML looks something like this:

  <div id="leftnav">
    <ul>
      <li>
        <a>Section A</a>
        <ul>
          <li>
            <a>Subsection A.1</a>
          </li>
        </ul>
      </li>
      <li>
        <a>Section B</a>
      </li>
    </ul>
  </div>

I think that the following javascript will accomplish expanding or compressing the nested list:

Event.observe(document, 'dom:loaded', function() 
{  
  $$('#leftnav li a').each(function(anchor) 
  {  
    anchor.observe('click', function(e)
    { 
      e.stop();
      var el = e.element();
      var next = el.next('ul');
      if (next)
      {
        next.toggle();
      }
      el.up('li').toggleClassName('active');
    });             
 });  
});
I was thinking the same thing. You also might want to bind a single handler to the leftnav element, and figure out which link was clicked in the event handler.
thoughtcrimes
Thanks guys for the responses. 'Hubology' your answer worked perfectly. As I had to tried to resolve this a long time ago, the only I was accomplishing were memory leaks in my JS code. 'thoughtcrimes', I like you suggestion as well. I'll have to see what I can do with that, as that will be helpful if I only want to have one nested <UL> showing at a time.
tbrady