Arrows to change a month in a calendar in JavaScript

Let's now make arrows below the calendar to change a month. Let's make some changes to the HTML code:

<div id="parent"> <div id="calendar"> <div class="info">Jan 2020</div> <table> <thead> <tr> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>Sat</th> <th>Sun</th> </tr> </thead> <tbody class="body"></tbody> </table> <div class="nav"> <a href="#" class="prev">←</a> <a href="#" class="next">→</a> </div> </div> </div>

Let's make changes to the CSS code:

#parent { text-align: center; } #calendar { display: inline-block; } #calendar td, #calendar th { padding: 10px; border: 1px solid black; text-align: center; } #calendar .nav, #calendar .info { text-align: center; } #calendar a { color: blue; font-size: 25px; text-decoration: none; } #calendar a:hover { color: red; } #calendar .active { color: red; }

Get references to arrows in variables:

let prev = calendar.querySelector('.prev'); let next = calendar.querySelector('.next');


Let's now discuss how to solve the problem. In fact, our calendar code is well extensible: we have the draw function that draws a calendar for a given month. Thus, when clicking on the arrow, we can redraw the calendar with a different month (and possibly year) number.

Here is an example of what we can do by clicking on the next month arrow:

next.addEventListener('click', function() { draw(body, getNextYear(year, month), getNextMonth(month)); });

As you can see, the functions getNextYear and getNextMonth are used here. Let's discuss what they should do.

As the name implies, the getNextYear function obtains the next year. This means that if it is December now, then when switching to the next month, the year should increase by 1. If it is not December, then the function should simply return the current year.

The getNextMonth function should get the next month. It will add one to the month number for all months except December. Well, for December, the next month will be January with the number 0.

Similar operations should be done by clicking on the button of the previous month:

prev.addEventListener('click', function() { draw(body, getPrevYear(year, month), getPrevMonth(month)); });

Implement an operation of the month change buttons.

Make the information above the calendar match the displayed month and year.