I’m having a problem with a piece of code and it’s driving me nuts. I’ve been stuck on this for hours, and the worst part is that I’m assuming it’s really simple; I just can’t figure it out.
I’m trying to make a simple event calendar using Javascript/jQuery. This is the simplified code that I have:
var currentMonth = 1;
if (currentMonth == 1) {
$("#prev-month").click( function() {
currentMonth = 12;
});
$("#next-month").click( function() {
currentMonth = 2;
});
}
if ( currentMonth == 2) {
$("#prev-month").click( function() {
currentMonth = 1;
});
$("#next-month").click( function() {
currentMonth = 3;
});
}
if ( currentMonth == 3) {
$("#prev-month").click( function() {
currentMonth = 2;
});
$("#next-month").click( function() {
currentMonth = 4;
});
}
if ( currentMonth == 4) {
$("#prev-month").click( function() {
currentMonth = 3;
});
$("#next-month").click( function() {
currentMonth = 5;
});
}
Now, every time I click the button with the ID “next-month”, it is always 2. If I click the button with the ID “prev-month”, it is always 12. It never changes. What am I doing wrong?
Your script code is only run once. You aren’t changing the click handlers after you clicked them, so those handlers will always give the same results.
But instead of fixing that it would be simpler to use a single handler for each button and using arithmetic to calculate the next/previous month instead of having 12 handlers which you change at runtime.