Reputation: 5442
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');
});
});
Upvotes: 4
Views: 204
Reputation: 9202
I think this is the cleanest way without chaining the HTML:
$(document).ready(function() {
$("#paylas_, #uyari_, #dahada_").click(function() {
var ids = ["#uyri", "#dhda", "#pyls"],
current = "#" + $(this)
.attr("id")
.replace(/_$/, "")
.replace(/a(.)/g, "$1");
delete ids[$.inArray(current, ids)];
$(ids.join(",")).slideUp();
$(current).slideToggle("normal");
});
});
Edit: removed span
in front
Upvotes: 2
Reputation: 76003
$(function() {//notice the shorter document.ready declaration :)
//setup a conversion from the clicked elements to the elements to slide up/down
var convert = {
paylas_ : '#pyls',
uyari_ : '#uyri',
dahada_ : '#dhda'
};
//select all the spans and bind the event handler to them, you can select multiple elements at once by separating the selectors with commas
$('#paylas_, #uyari_, #dahada_').click(function() {
//slide up all the spans except for the on associated with the currently clicked element
$('#uyri, #dhda, #pyls').not(this).slideUp();
//slide toggle the currently clicked element
$(convert[this.id]).slideToggle('normal');
});
});
Here is a demo: http://jsfiddle.net/yPxHq/1/
Upvotes: 2
Reputation: 154858
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.
Upvotes: 6
Reputation: 10258
This is a quick refactor which may help a bit
$(document).ready(function() {
clickFuntion("paylas","uyri","dhda","pyls");
clickFuntion("uyari","pyls","dhda","uyri");
clickFuntion("dahada","pyls","uyri","dhda");
function clickFuntion(var1,va2,var3,var4){
$('span#"+var1+"_').click(function() {
$('#"+var2+"').slideUp();
$('#"+var3+"').slideUp();
$('#"+var4+"').slideToggle('normal');
});
}
});
Upvotes: 1