Reputation: 117
I want to create a For loop for a series of 'click' events on my page. I'm creating a timetable where clicking on a Day button will display the events assigned to that day in a div box.
HTML
<div class="cwt-buttons">
<a id="cwt-button1">Monday</a>
<a id="cwt-button2">Tuesday</a>
<a id="cwt-button3">Wednesday</a>
<a id="cwt-button4">Thursday</a>
<a id="cwt-button5">Friday</a>
<a id="cwt-button6">Saturday</a>
<a id="cwt-button7">Sunday</a>
</div>
<div id="cwt-timetable">
<div class="current">Housework</div>
<div class="cwt-Day1">Kickboxing</div>
<div class="cwt-Day2">Homework</div>
<div class="cwt-Day3">Yoga</div>
<div class="cwt-Day4">Eating</div>
<div class="cwt-Day5">Fasting</div>
<div class="cwt-Day6">Running</div>
<div class="cwt-Day7">Funeral</div>
</div>
JS
$(function() {
for ( var i = 1; i < 8; i++ ) {
var clickedButton = $("#cwt-button"+i);
$(clickedButton).click(function() {
var currentDay = $('#cwt-timetable div.current');
var selectedDay = $('#cwt-timetable div.cwt-Day'+i);
currentDay.removeClass('current').addClass('previous');
(selectedDay).css({ opacity: 0.0 }).addClass('current').animate({ opacity: 1.0 }, 1000,
function() {
currentDay.removeClass('previous');
});
})
}
});
The JavaScript works fine when I have the exact value in e.g. "#cwt-button1"
It just doesn't work when I concatenate the 'i' counter in the loop.
Can anyone see where I'm going wrong? Or am I do something JavaScript can't handle?
Upvotes: 6
Views: 2478
Reputation: 3543
This is just the same old issue that gets asked multiple times a day. All your functions created in the loop are created in the same variable scope, so they share the same i
variable.
To scope a variable you need a function invocation. jQuery's $.each()
is a handy way to do this:
$(function () { // -----------v-----scoped to the function
$.each(Array(7), function(i) {
var clickedButton = $('#cwt-button' + (++i));
$(clickedButton).click(function () {
var currentDay = $('#cwt-timetable div.current');
// --------using scoped `i`------------------------v
var selectedDay = $('#cwt-timetable div.cwt-Day' + i);
currentDay.removeClass('current').addClass('previous');
(selectedDay).css({
opacity: 0.0
}).addClass('current').animate({
opacity: 1.0
}, 1000, function () {
currentDay.removeClass('previous');
});
});
});
});
Upvotes: 2