More efficient jQuery

I have the following code that controls the presentation of an interdependent group. The current code is working, I am wondering if there is a way to arrange the code in order to reduce duplication.

    $('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
+3
source share
2 answers

This adds a bit of complexity, but changes more flexibly. If you want to change the duration or add effects to the slide, you do not need to edit the code in 9 places, only 1 or 2. If you do not need additional flexibility, you can simplify some of the code - for example, delete a function getDurationand 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;
});     
+4
source
// 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;
});
0
source

Source: https://habr.com/ru/post/1716434/


All Articles