Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the shortest way to do this thing on jquery?

Here is what I have and it works just fine but could you tell me if there is any short and clean coding way to do this?

$(document).ready(function() {  
    $('span#paylas_').click(function() {
        $('#uyri').slideUp();
        $('#dhda').slideUp();
        $('#pyls').slideToggle('normal');
    });
    $('span#uyari_').click(function() {
        $('#pyls').slideUp();
        $('#dhda').slideUp();
        $('#uyri').slideToggle('normal');
    });
    $('span#dahada_').click(function() {
        $('#pyls').slideUp();
        $('#uyri').slideUp();
        $('#dhda').slideToggle('normal');
    });     
});
like image 902
Ali Demirci Avatar asked Dec 21 '22 04:12

Ali Demirci


1 Answers

If you give data-toggle attributes to your elements like this:

<span id="paylas_" data-toggle="#pyls"></span>

then you can combine the selectors and use .data("toggle") to get the appropriate selector:

$(document).ready(function() {
    var toggles = {};

    $('#paylas_, #uyari_, #dahada_').click(function() {
        var cached = this.id in toggles;

        if(!cached) {
            toggles[this.id] = $(this).data("toggle");
        }

        var toggle = toggles[this.id];

        $('#uyri, #dhda, #pyls').not(toggle).slideUp();
        $(toggle).slideToggle('normal');
     });
});

If you use data-toggle only for those elements, then you can also do:

$('[data-toggle]').click(function() {

I can't really make up something of the IDs but if there is a certain structure you could possibly generalize the second list of selectors as well.

like image 125
pimvdb Avatar answered Jan 02 '23 09:01

pimvdb