views:

47

answers:

1

I've got a bunch of 'project' divs that I want to expand when they're clicked on. If there's already a project open, I want to hide it before I slide out the new one. I also want to stop clicks on an already open project from closing and then opening it again.

Here's an example of what I mean (warning - wrote the code in the browser):

        $('.projects').click(function() {
          var clicked_project = $(this);

          if (clicked_project.is(':visible')) {
            clicked_project.height(10).slideUp();
            return;
          }

          var visible_projects = $('.projects:visible');
          if (visible_projects.size() > 0) {
            visible_projects.height(10).slideUp(function() {
              clicked_project.slideDown();
            });
          } else {
            clicked_project.slideDown();
          }
        });

Really, my big issue is with the second part - it sucks that I have to use that if/else - I should just be able to make the callback run instantly if there aren't any visible_projects.

I would think this would be a pretty common task, and I'm sure there's a simplification I'm missing. Any suggestions appreciated!

+1  A: 

slideToggle?

$('.projects').click(function() {
  var siblings = $(this).siblings('.projects:visible');
  siblings.slideUp(400);
  $(this).delay(siblings.length ? 400 : 0).slideToggle();
});

Used a delay rather than a callback because the callback is called once per matched item. This would lead to multiple toggles if multiple items were visible.

wombleton
Nice. That does the job, but is there any way to only do the toggle after the slide up has finished? If I put it in a callback, it doesn't execute if there aren't any visible projects.
zaius
Good point on the callbacks. Only problem with the delay is that it will still delay the initial slidedown even if there is no siblings visible.
zaius
if there are siblings, siblings.length will be truthy.
wombleton
Nice! I like it! Thanks for sticking with me :)
zaius