Simple Month Calendar

AleMonteiro 3 Tallied Votes 2K Views Share

Hello everybody.

I'm starting to build an event calendar for employees in my company, and the first thing I needed was an working calendar to build from, so I wrote a simple one.

Hope it can be usefull for someone.

Cheers.

JorgeM commented: great job. would like to see your progress as you further develop it... +12
LastMitch commented: Nice! +11
<!DOCTYPE html>
<html>

<head>
	
	<title>Simple Month Calendar</title>
	
	<script type="text/javascript">
		
		// Author: Alê Monteiro
		// Created: 2013-03-06
		// E-mail: lu.ale.monteiro@gmail.com
				
		// P.S. I'm from Brazil, so the names of the weeks and months are in Portuguese.
		
		var Calendar = function(divId) {
			
			//Store div id
			this.divId = divId;
			
			// Days of week, starting on Sunday
			this.DaysOfWeek = [
				'Domingo',
				'Segunda',
				'Terça',
				'Quarta',
				'Quinta',
				'Sexta',
				'Sábado'
			];
			
			// Months, stating on January
			this.Months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembto', 'Outubro', 'Novembro', 'Dezembro' ];
			
			// Set the current month, year
			var d = new Date();
			
			this.CurrentMonth = d.getMonth();
			this.CurrentYear = d.getFullYear();
			
		};
		
		// Goes to next month
		Calendar.prototype.nextMonth = function() {
			if ( this.CurrentMonth == 11 ) {
				this.CurrentMonth = 0;
				this.CurrentYear = this.CurrentYear + 1;
			}
			else {
				this.CurrentMonth = this.CurrentMonth + 1;
			}
			this.showCurrent();
		};
		
		// Goes to previous month
		Calendar.prototype.previousMonth = function() {
			if ( this.CurrentMonth == 0 ) {
				this.CurrentMonth = 11;
				this.CurrentYear = this.CurrentYear - 1;
			}
			else {
				this.CurrentMonth = this.CurrentMonth - 1;
			}
			this.showCurrent();
		};
		
		// Show current month
		Calendar.prototype.showCurrent = function() {
			this.showMonth(this.CurrentYear, this.CurrentMonth);
		};
		
		// Show month (year, month)
		Calendar.prototype.showMonth = function(y, m) {
			
			var d = new Date()
				// First day of the week in the selected month
				, firstDayOfMonth = new Date(y, m, 1).getDay()
				// Last day of the selected month
				, lastDateOfMonth =  new Date(y, m+1, 0).getDate()
				// Last day of the previous month
				, lastDayOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();
				
			
			var html = '<table>';
			
			// Write selected month and year
			html += '<tr><td colspan="7">' + this.Months[m] + ' - ' + y + '</td></tr>';
			
			// Write the header of the days of the week
			html += '<tr>';
			for(var i=0; i < this.DaysOfWeek.length;i++) {
				html += '<td>' + this.DaysOfWeek[i] + '</td>';
			}
			html += '</tr>';
			
			// Write the days
			var i=1;
			do {
				
				var dow = new Date(y, m, i).getDay();
				
				// If Sunday, start new row
				if ( dow == 0 ) {
					html += '<tr>';
				}
				// If not Sunday but first day of the month
				// it will write the last days from the previous month
				else if ( i == 1 ) {
					html += '<tr>';
					var k = lastDayOfLastMonth - firstDayOfMonth+1;
					for(var j=0; j < firstDayOfMonth; j++) {
						html += '<td class="not-current">' + k + '</td>';
						k++;
					}
				}
				
				// Write the current day in the loop
				html += '<td>' + i + '</td>';
				
				// If Saturday, closes the row
				if ( dow == 6 ) {
					html += '</tr>';
				}
				// If not Saturday, but last day of the selected month
				// it will write the next few days from the next month
				else if ( i == lastDateOfMonth ) {
					var k=1;
					for(dow; dow < 6; dow++) {
						html += '<td class="not-current">' + k + '</td>';
						k++;
					}
				}
				
				i++;
			}while(i <= lastDateOfMonth);
			
			// Closes table
			html += '</table>';
			
			// Write HTML to the div
			document.getElementById(this.divId).innerHTML = html;
		};
		
		// On Load of the window
		window.onload = function() {
			
			// Start calendar
			var c = new Calendar("divCalendar");			
			c.showCurrent();
			
			// Bind next and previous button clicks
			getId('btnNext').onclick = function() {
				c.nextMonth();
			};
			getId('btnPrev').onclick = function() {
				c.previousMonth();
			};
		}
		
		// Get element by id
		function getId(id) {
			return document.getElementById(id);
		}
	
	</script>

	<style type="text/css">
		
		td.not-current {
			color: #777;
		}
		
	</style>
	
	
</head>

<body>
	
	<div id="divCalendar">
			
	</div>
	
	<button id="btnPrev" type="button">Previous</button>
	<button id="btnNext" type="button">Next</button>
	
	
</body>

</html>
JorgeM 958 Problem Solver Team Colleague Featured Poster

great start on this project. thanks for sharing. something like this can definatley be useful in future projects.

Member Avatar for LastMitch
LastMitch

Thanks for sharing!

Mike_40 0 Newbie Poster

I re-wrote this in jQuery, Bootstrap, and English

<script>
    var Calendar = function($calendar, $title) {

        //Store div id
        this.$e = $calendar;
        this.$t = $title;

        this.$e.addClass("grid-calendar");

        // Days of week, starting on Sunday
        this.DaysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

        // Months, stating on January
        this.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        // Set the current month, year
        var d = new Date();

        this.CurrentMonth = d.getMonth();
        this.CurrentYear = d.getFullYear();

    };

// Goes to next month
    Calendar.prototype.nextMonth = function() {
        if ( this.CurrentMonth == 11 ) {
            this.CurrentMonth = 0;
            this.CurrentYear = this.CurrentYear + 1;
        }
        else {
            this.CurrentMonth = this.CurrentMonth + 1;
        }
        this.showCurrent();
    };

// Goes to previous month
    Calendar.prototype.previousMonth = function() {
        if ( this.CurrentMonth == 0 ) {
            this.CurrentMonth = 11;
            this.CurrentYear = this.CurrentYear - 1;
        }
        else {
            this.CurrentMonth = this.CurrentMonth - 1;
        }
        this.showCurrent();
    };

// Show current month
    Calendar.prototype.showCurrent = function() {
        this.showMonth(this.CurrentYear, this.CurrentMonth);
    };

// Show month (year, month)
    Calendar.prototype.showMonth = function(y, m) {

        var d = new Date()
            // First day of the week in the selected month
            , firstDayOfMonth = new Date(y, m, 1).getDay()
            // Last day of the selected month
            , lastDateOfMonth =  new Date(y, m+1, 0).getDate()
            // Last day of the previous month
            , lastDayOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();

        this.$e.html("");

        this.$t.html(this.Months[m] + '<span class="year">' + y + '</span>');

        var $header = $('<div class="row calendar-week-header"></div>');
        var $rowtemplate = $('<div class="row calendar-week"></div>');

        // Write the header of the days of the week
        for(var i=0; i < this.DaysOfWeek.length;i++) $header.append('<div class="col-xs-1 grid-cell"><span>' + this.DaysOfWeek[i] + '</span></div>');

        this.$e.append($header);

        var $row = $rowtemplate.clone(true, true);

        // Write the days
        var i = 1;
        do {

            var dow = new Date(y, m, i).getDay();

            // If Sunday, start new row
            if ( dow == 0 ) $row = $rowtemplate.clone(true, true);

            // If not Sunday but first day of the month
            // it will write the last days from the previous month
            else if ( i == 1 ) {
                $row = $rowtemplate.clone(true, true);

                var k = lastDayOfLastMonth - firstDayOfMonth+1;
                for(var j=0; j < firstDayOfMonth; j++) {
                    $row.append('<div class="col-xs-1 grid-cell previous-month"><span>' + k + '</span></div>');
                    k++;
                }
            }

            // Write the current day in the loop
            $row.append('<div class="col-xs-1 grid-cell"><span>' + i + '</span></div>');

            // If Saturday, closes the row
            if ( dow == 6 ) {
                this.$e.append($row);
            }
            // If not Saturday, but last day of the selected month
            // it will write the next few days from the next month
            else if ( i == lastDateOfMonth ) {
                var k=1;
                for(dow; dow < 6; dow++) {
                    $row.append('<div class="col-xs-1 grid-cell previous-month"><span>' + k + '</span></div>');
                    k++;
                }
                this.$e.append($row);
            }

            i++;
        } while(i <= lastDateOfMonth);

    };

    $(window).load(function(){
        // Start calendar
        var c = new Calendar($('.calendar'), $('.ttl'));
        c.showCurrent();

        // Bind next and previous button clicks
        $('.nxt').click( function() {
            c.nextMonth();
        });
        $('.prv').click( function() {
            c.previousMonth();
        });
    });
</script>
<style type='text/scss'> // This is in sass.

      $min-width: 320px;
      $number-of-days: 7;
      $column-width: percentage(1/$number-of-days);

      .grid-calendar {
        .row {
          margin: 0;
        }

        .calendar-week .grid-cell {
          background-color: #f6f6f6;
          border: 1px solid #fff;
        }

        .calendar-week-header .grid-cell > div > div {
          padding-bottom: 10px;
          height: auto;
        }

        .grid-cell {
          display: inline-block;
          float: left;
          min-height: 1px;
          padding: 0;
          position: relative;
          width: $column-width;

          &.previous-month {
            color: #a6a6a6;
          }

          &.next-month {
            background-color: #e1e1e1;
          }

        }

</style>
Member Avatar for diafol
diafol

Thanks for the code. You'd be better posting this as a code snippet rather than as a post in a well dead article.

Member Avatar for diafol
diafol

I meant separate snippet!

Mike_40 0 Newbie Poster

I found this on google when I was searching for how to do this for a project. After I modernized it I felt that I should update the original post in case someone else found it and wanted to do the same thing I was doing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.