[jQuery] Registering the value of variable instead of the variable itself in a loop
Hello,
I'm new to jQuery and I am currently working on google gadget which
has some animations.
I have wrote the jQuery code and manage to make it work:
$('#itemn').click(function() {
if ($("#tabcontentn").is(":hidden")) {
if(active == "init") {
$("#tabcontentn").slideDown(300);
active = "#tabcontentn";
} else {
$(active).slideUp(300, function() {
$("#tabncontent").slideDown(300);
active = "#tabcontentn";
});
}
} else {
$("#tabcontentn").slideUp(300);
}
}
The problem has arisen after I decided to create a single for loop
instead of binding all elements one by one. Although I managed to get
it work with some workaround I'm not happy with the result:
for(var i = 1; i < 6;i ++) {
item = '#item'+i;
$(item).click(function() {
alert(vts(this));
if ($(vts(this)).is(":hidden")) {
if(active == "init") {
$(vts(this)).slideDown(300);
active = vts(this);
} else {
that = vts(this);
$(active).slideUp(300, function() {
$(that).slideDown(300);
active = that;
});
}
} else {
$(vts(this)).slideUp(300);
active = 'init';
}
});
}
function vts(e) {
var t;
t = e.id;
t = t.replace(/item/ig, '');
t = '#tabcontent'+t;
return t;
}
what I really want is creating some kind of code like this:
for(var i = 1; i < 6; i++) {
var item = '#item'+i;
var element = '#tabcontent'+i;
$(item).click(function() {
if ($(element).is(":hidden")) {
if(active == "init") {
$(element).slideDown(300);
active = element;
} else {
$(active).slideUp(300, function() {
$(element).slideDown(300);
active = element;
});
}
} else {
$(element).slideUp(300);
}
}
}
The problem with the above code is the $(element) stays as the last
element (#tabcontent5). I need to find a way to register that element
variable as a static value instead of the variable itself.
Any help would be appreciated.
Ozberk