views:

175

answers:

2

I have the following code that controls the presentation of an interdependent group. The current code works, I'm wondering if there is a way to streamline the code so less is duplicated.

 $('div.locUpd').hide();
 $('div.locDel').hide();
 $('div.addLocation').hide();
 $('a.edit').click(function(){
  $(this).parent().nextAll('div.locUpd').slideToggle(400);
  $('div.locDel').slideUp(400);
  $('div.addLocation').slideUp(400); 
  return false;
 });  
 $('a.del').click(function(){
  $(this).parent().nextAll('div.locDel').slideToggle(400);
  $('div.locUpd').slideUp(400);
  $('div.addLocation').slideUp(400); 
  return false;
 });  
 $('p.buslocadd').click(function(){
  $(this).prev('div.addLocation').slideToggle(400);
  $('div.locUpd').slideUp(400);
  $('div.locDel').slideUp(400); 
  return false;
 });

Is there a more efficient way to write this?

Edit----------------

Here's the HTML structure:

div.mbuslocations
    div.location
     span.lmeta
      a.edit
      a.del
     div.locUpd
     div.locDel
div.addLocation
p.buslocadd
+4  A: 

This adds a little bit of complexity, but is more flexible to change. If you want to change the duration or add effects to sliding you don't have to edit the code in 9 places, just 1 or 2. If you don't need the added flexibility, you could simplify some of the code - for example remove the getDuration function and just hard code 400.

function getDuration() {
  return 400;
}

function slideToggleDiv(t, selector) {
  t.parent().nextAll(selector).slideToggle(getDuration());
}

function slideUpDiv(selected) {
  selected.slideUp(getDuration());
}

$('div.locUpd, div.locDel, div.addLocation').hide();

$('a.edit').click(function(){
  slideToggleDiv($(this), 'div.locUpd');
  slideUpDiv($('div.locDel, div.addLocation'));      
  return false;
});             

$('a.del').click(function(){
  slideToggleDiv($(this), 'div.locDel');
  slideUpDiv($('div.locUpd, div.addLocation'));      
  return false;
});     

$('p.buslocadd').click(function(){
  slideToggleDiv($(this), 'div.locUpd');
  slideUpDiv($('div.locDel, div.locUpd'));      
  return false;
});
Andy Gaskell
A: 
// Untested.

var parts = {
    '.edit': '.locUpd',
    '.del': '.locDel',
    '.buslocadd': '.addLocation'
},
    selectedParts = $(),
    root = document,
    i;

// TODO Make jQuery-ish.
for(i in parts) {
    selectedParts = selectedParts.add($(parts[i], root));
}

// Hide everything.
selectedParts.hide();

// Click to hide all but this (kinda?).
selectedParts.click(function() {
    for(i in parts) {
        if($(this).is(i)) {
            $(this).parent().nextAll(parts[i]).toggleSlide(400);
        } else {
            $(parts[i], root).slideUp(400);
        }
    }

    return false;
});
strager