Dynamic calendar of months JavaScript

1

I'm a beginner in Javascript.

I need to make a calendar that shows only the months.

For example:

We are in September. The calendar will show from September (2016) to August (2017).

With the code below, I can print the months from January to December. But I need him to show from the current month up to 12 months ahead. Can you help me?

            window.onload = function calendar() {
                var a = new Date();
                var b = a.getMonth();
                var months = [
                    "Janeiro",
                    "Fevereiro",
                    "Março",
                    "Abril",
                    "Maio",
                    "Junho",
                    "Julho",
                    "Agosto",
                    "Setembro",
                    "Outubro",
                    "Novembro",
                    "Dezembro"
                ];
                var i = months[i];
                for (i = 0; i <= 11; i++) {
                    document.getElementsByClassName("month-time")[i].innerHTML = months[i];
                }
            }
    
asked by anonymous 30.09.2016 / 04:46

1 answer

1

You can do this:

var a = new Date();
var b = a.getMonth();
var months = [
    "Janeiro",
    "Fevereiro",
    "Março",
    "Abril",
    "Maio",
    "Junho",
    "Julho",
    "Agosto",
    "Setembro",
    "Outubro",
    "Novembro",
    "Dezembro"
];
window.onload = function calendar() {
    var meses = [];
    for (i = b; i <= b + 11; i++) {
        var mes = i > 11 ? months[i - 12] : months[i];
        meses.push(mes);
    }
    [].forEach.call(document.getElementsByClassName("month-time"), function(el, i) {
        el.innerHTML = meses[i];
    })
}
.month-time:first-of-type {color: blue;}
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>
<div class="month-time"></div>

In this way you create the array in a loop and then you call all the elements at once and iteraes them by filling in the correct month

    
30.09.2016 / 15:43