Reputation: 1223
I'm building my small calendar with plain javascript (so please no jquery) and I have trouble to make the prev month display So far this is my code for get previous month:
document.getElementById("prev-month").addEventListener("click", function(e) {
console.log('first', prevMonth);
prevMonth = monthNamesArray[currentMonth - 1]; //Array with all the month labels like ['Jan', 'Feb', 'Mar'];
month.innerHTML = '<td>'+ prevMonth +'</td>'; //Here i replace the html cell where the month is display
console.log('second', prevMonth);
});
The console.log of the two debugger is: First click: first undefined second September(the previous month) Second click: first September second September
Why the during the second click the second console log didn't became second August ? Why the prevMonth go back just one month?
Any help, in particular an explanation, is really appreciated
Upvotes: 0
Views: 46
Reputation: 3388
Is there any reason why you need prevMonth, as to keep it updating correctly you would ideally write it as:
currentMonth = monthNamesArray[(currentMonth==0)? 11 : currentMonth-1];
The ternary operator ensures that at January you don't go monthNamesArray[-1]
, but it instead wraps back to monthNamesArray[11]
.
EDIT: Both directions, the direction variable can be any size integer value, so you could go direction = -2 and it will go backwards 2 months. currentMonthIndex is the index for the current month 0 to 11.
var remainder = (currentMonthIndex + direction) % 12;
currentMonth = monthNamesArray[Math.floor(remainder >= 0 ? remainder : remainder + 12)];
Upvotes: 1