Dynamic calendar of Javascript months

Asked

Viewed 467 times

2

am a beginner in Javascript.

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

For example:

It is September now. 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 you from the present month 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];
                }
            }

  • I only saw now these two unnecessary variables at the beginning of the function.

1 answer

2


You can do it like 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>

This way you create the array in a loop and then call all the elements of a single time and iterates filling them with the correct month

  • 1

    It worked fine! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.