Click here to Skip to main content
15,888,527 members
Articles / Web Development / HTML
Article

A JavaScript Weekly Calendar

Rate me:
Please Sign up or sign in to vote.
4.76/5 (30 votes)
14 Feb 2006CPOL1 min read 372.3K   2.8K   67   88
This calendar can be used as a date picker or to select a weekly day range in the selected month.

Sample Image - js_weekly_calendar_IE.jpg

Introduction

The calendar generated by this script can be used as a date picker or to select a weekly day range in the selected month. This script has been tested only with Internet Explorer 6.0, Firefox 1.0.7, and Opera 8.51 on a Windows 2003 Server.

Usage

Using this calendar, you can select the start week day, the default is Monday. The calendar's layout is customizable by CSS. To use it, you must insert the following HTML code in the head section of your page:

HTML
// insert this code in the head section
// use this css to modify the calendar layout
<LINK REL=StyleSheet HREF="calendar.css" TYPE="text/css">
// include the calendar javascript
<SCRIPT LANGUAGE="JavaScript" 
         SRC="weeklycalendar.js"></SCRIPT>
<script language="javascript">
    // call the function to build the calendar
    // function's param specify the first day of week 
    // 0=Sunday, 1 = Monday, ..., 6=Saturday
    buildWeeklyCalendar(1);
</script>

If the first day of the week is Monday, the column week contains the week number, otherwise it shows the "<" symbol.

Sample Image - js_weekly_calendar_firefox.jpg

The calendar is dynamically added to the HTML page and it is contained in a div element. To display the calendar, it is necessary to call the w_displayCalendar function. This function accepts two input parameters; they must be the existing element IDs used by the script to return values.

JavaScript
//
// display calendar
//
function w_displayCalendar(linkedId1, linkedId2) 
{
    w_linkedInputText_1 = linkedId1;
    w_linkedInputText_2 = linkedId2;
    
    w_renderCalendar(0);
    if(navigator.userAgent.indexOf("MSIE") != -1) 
    {
        weeklyCalendar.style.left=
          window.event.x+document.body.scrollLeft;
        weeklyCalendar.style.top=
          window.event.y+document.body.scrollTop;
    } 
    else if ((navigator.appName.indexOf("Netscape") != -1) || 
             (navigator.appName.indexOf("Opera") != -1))
    {
        document.getElementById('weeklyCalendar').style.left=gx + 5;
        document.getElementById('weeklyCalendar').style.top=gy + 5;
    }
    document.getElementById('weeklyCalendar').style.visibility = "visible";
}

Using the calendar as a date picker, it automatically fills an input text element passing its ID as a parameter of the w_displayCalendar function.

HTML
<tr>
   <td style="height: 78px">Date picker</td><td style="height: 78px">
      <!--  this is the datepicker input text -->    
      <input type="text"  name="DatePicker" id="DatePicker" size="35" maxlength="80">
      <!--  attach the w_displayCalendar function to the onClick event -->
      <input type="button" value="..." 
         onClick="w_displayCalendar('DatePicker',null);">
   </td>
</tr>

Using the calendar as a weekly range selector, clicking on the week number or the < symbol, it automatically fills the two input text.

HTML
<tr>
    <td style="height: 131px">Weekly Range Selector</td>
      <!--  this is start range input text -->    
      <td style="height: 131px">Start day:<input type="text" 
         name="WeeklyDateStart" id="WeeklyDateStart" 
         size="35" maxlength="80"><br />
      <!--  this is end range input text -->
      End day: <input type="text"  name="WeeklyDateEnd" 
         id="WeeklyDateEnd" size="35" maxlength="80">
      <!--  attach the w_displayCalendar function to the onClick event -->
      <input type="button" value="..." 
        onClick="w_displayCalendar('WeeklyDateStart','WeeklyDateEnd');">
   </td>
</tr>

Sample Image - js_weekly_calendar_opera.jpg

New Feature

Now you can use the calendar as a simple date picker using the new function w_displayDatePicker. This function shows the calendar and automatically hides the column week using a new CSS class.

HTML
<tr>
   <td style="height: 78px">Date picker</td>
   <td style="height: 78px">
      <!--  this is the datepicker input text -->
      <input type="text"  name="DatePicker" 
             id="DatePicker" size="35" maxlength="80">
      <!--  attach the w_displayCalendar function to the onClick event -->
      <input type="button" value="..."
         onClick="w_displayDatePicker('DatePicker');">
   </td>
</tr>

Conclusion

The Zip source file contains the weekly calendar script, the CSS and two demo HTML pages.

I hope you enjoy this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: How to set WeekDate the first day of row ?! exactly that it is one day of the previous month Pin
cpsaran15-Sep-09 4:19
cpsaran15-Sep-09 4:19 
GeneralRe: How to set WeekDate the first day of row ?! exactly that it is one day of the previous month [modified] Pin
Massimo Beatini15-Sep-09 21:38
Massimo Beatini15-Sep-09 21:38 
GeneralRe: How to set WeekDate the first day of row ?! exactly that it is one day of the previous month [modified] Pin
DaFleaster19-Mar-12 8:20
DaFleaster19-Mar-12 8:20 
GeneralRe: How to set WeekDate the first day of row ?! exactly that it is one day of the previous month Pin
Massimo Beatini15-Sep-09 21:51
Massimo Beatini15-Sep-09 21:51 
QuestionWay to pass date to calendar ? Pin
bluter13-Oct-06 4:25
bluter13-Oct-06 4:25 
AnswerRe: Way to pass date to calendar ? Pin
Massimo Beatini14-Nov-06 23:10
Massimo Beatini14-Nov-06 23:10 
QuestionDisable all the days before today! Pin
webmangr9-Oct-06 3:27
webmangr9-Oct-06 3:27 
AnswerRe: Disable all the days before today! Pin
Massimo Beatini9-Oct-06 4:27
Massimo Beatini9-Oct-06 4:27 
Hi,
as you wrote before in IE my function didn't work right.

I solve the problem with this new function (I hope Smile | :) !).
You can also try the new script here: http://www.code4dotnet.com/test/cal_demo1.htm[^]



Download the complete script here weeklycalendar.js or substitute the old w_writeDayNumber function with the following one:

<code lang="cs">
//
//
//
function w_writeDayNumber(d)
{
	var dd = new Date(d);
	var temp = new Date(d);
	
	
	// reset data array
	for (i=0;i<6;i++)
	{

 		for (j=0;j<7;j++)
 		{
			document.getElementById("w_c" +i+""+j).innerHTML= "";
			document.getElementById("w_c" +i+""+j).className = "day_out";
        
            var object;
            object = document.getElementById("w_c" +i+""+j);
            try
            {
                if(window.removeEventListener){ // Mozilla, Netscape, Firefox     
                    object.removeEventListener('click', w_setDate, false);
                } else { // IE
                    object.detachEvent('onclick', w_setDate);
                }
            }
            catch(e){}

 	    }
        document.getElementById("week_" +i).innerHTML = '';
	}
	
	// set to the first day of the month
	dd.setDate(1);
	
	// fill data array
	i = 0;
	j = 0;

    // previous month's days
    j = dd.getDay() - w_StartOfWeek;
    if (j<0)
        j = 7 + j;
    
    if (j > 0)
    {
        temp.setDate(dd.getDate()-1);
        for (k=j-1; k>=0; k--)
        {
			document.getElementById("w_c" +i+""+k).innerHTML= temp.getDate();
		    if ((weekend_pos[0] == k) || (weekend_pos[1] == k))
		        document.getElementById("w_c" +i+""+k).className = "weekends_out";
		    else
			    document.getElementById("w_c" +i+""+k).className = "day_out";

            temp.setDate(temp.getDate()-1);
        }
    }

	var week = -1;
    var iStartWeek = -1;
    var iEndWeek = -1;
    var weekEl;
    var dayval;

	do 
	{
	    // get the position according to
	    // StartOfWeek
	    j = dd.getDay() - w_StartOfWeek;
	    if (j<0)
	        j = 7 + j;
	
	    if (iStartWeek==-1)
	        iStartWeek = j;
        iEndWeek = j;
        	        
		dayval = dd.getDate();



	    // get the week number
	    if (week < 0)
	        week = w_getWeek(w_d.getFullYear(), w_d.getMonth(), dayval);
	        
		document.getElementById("w_c" +i+""+j).innerHTML= dayval;
		
		// set week ends layout
		if ((weekend_pos[0] == j) || (weekend_pos[1] == j))
		    document.getElementById("w_c" +i+""+j).className = "weekends";
		else
		    document.getElementById("w_c" +i+""+j).className = "day";
        {
            // set today layout 
            var today = new Date();
			
	    if ((today.getDate() ==  dayval) && 
		(today.getMonth() == w_d.getMonth()) && 
		(today.getFullYear() == w_d.getFullYear()) )
		    document.getElementById("w_c" +i+""+j).className = "today";
        }

        ////////
        // dinamically set the onclick event
        // only on the day of the selected month
        ////////

        var object = document.getElementById("w_c" +i+""+j);
        object.rownumber = i;
        object.colnumber = j;

// add event only to a date >= today
// and not a week end
      		if ((weekend_pos[0] != j) && (weekend_pos[1] != j))
      		{
                if (w_d.getFullYear() >= today.getFullYear())
                {
    
                    if ( (w_d.getMonth() > today.getMonth())
                        ||
                        ( (w_d.getMonth() == today.getMonth()) && (dayval >= today.getDate()) )
                        )
                    { 

                        if(window.addEventListener){ // Mozilla, Netscape, Firefox     
                            object.addEventListener('click', w_setDate, false);
                        } else { // IE
                            object.attachEvent('onclick', w_setDate);
                        }
                    }
                }
           }


        ///////
        
        
	    if (week < 0)
	        document.getElementById("week_" +i).innerHTML = '';
	    else if (w_StartOfWeek != 1)
	        document.getElementById("week_" +i).innerHTML = "<";
	    else
	        document.getElementById("week_" +i).innerHTML = week;

        weekEl = document.getElementById("week_" +i);

        // if HideWeekCol change the class
        // hide the week col and its header
        if (HideWeekCol) 
        {
            weekEl.className = "weekhidden";
            document.getElementById("weekHeader").className = "weekhidden";
        }
        else
        {
            document.getElementById("weekHeader").className = "week";
            weekEl.className = "weeksel";
        }
        
        
        
		if (j == 6) 
		{
            ////////
            // dinamically set the onclick event
            // on the week number
            ////////
            weekEl.startweek = iStartWeek;
            weekEl.endweek = iEndWeek;
            weekEl.rowweek = i;

            // removed to prevent click on week number

//            if(window.addEventListener){ // Mozilla, Netscape, Firefox
//                weekEl.addEventListener('click', w_SetWeekDate, false);
//            } else { // IE
//                weekEl.attachEvent('onclick', w_SetWeekDate);
//            }
            ///////

		    week = -1;
		    iStartWeek = -1;
		    iEndWeek = -1;
		    i++;
		}
	
		dd.setDate(dd.getDate() + 1);
	
	} while (dd.getDate() != 1);
	
	if ((iStartWeek!=-1) && (iEndWeek!=-1))
	{
        weekEl = document.getElementById("week_" +i);
        
        ////////
        // dinamically set the onclick event
        // on the week number
        ////////
        weekEl.startweek = iStartWeek;
        weekEl.endweek = iEndWeek;
        weekEl.rowweek = i;

        if(window.addEventListener){ // Mozilla, Netscape, Firefox
            weekEl.addEventListener('click', w_SetWeekDate, false);
        } else { // IE
            weekEl.attachEvent('onclick', w_SetWeekDate);
        }
        ///////
    }
    
    // next month's days
    if ((j < 7))
    {
        temp = dd;
        for (k=j+1; k<7; k++)
        {
			document.getElementById("w_c" +i+""+k).innerHTML= temp.getDate();
	        if ((weekend_pos[0] == k) || (weekend_pos[1] == k))
	            document.getElementById("w_c" +i+""+k).className = "weekends_out";
	        else
			    document.getElementById("w_c" +i+""+k).className = "day_out";
            temp.setDate(temp.getDate()+1);
        }
    }


}
</code>

Bye
Massimo
GeneralRe: Disable all the days before today! Pin
webmangr9-Oct-06 21:31
webmangr9-Oct-06 21:31 
GeneralRe: Disable all the days before today! Pin
webmangr9-Oct-06 21:38
webmangr9-Oct-06 21:38 
GeneralRe: Disable all the days before today! Pin
webmangr9-Oct-06 21:44
webmangr9-Oct-06 21:44 
GeneralRe: Disable all the days before today! Pin
Massimo Beatini9-Oct-06 23:08
Massimo Beatini9-Oct-06 23:08 
GeneralRe: Disable all the days before today! Pin
Massimo Beatini9-Oct-06 22:38
Massimo Beatini9-Oct-06 22:38 
AnswerRe: Disable all the days before today! Pin
clausont24-May-08 6:19
clausont24-May-08 6:19 
Generalsmart navigation problem Pin
shesho64211-Sep-06 2:07
shesho64211-Sep-06 2:07 
GeneralInformations about calendar script Pin
Enrico Amisano7-Sep-06 6:51
Enrico Amisano7-Sep-06 6:51 
AnswerRe: Informations about calendar script Pin
Massimo Beatini8-Sep-06 4:58
Massimo Beatini8-Sep-06 4:58 
QuestionRe: Informations about calendar script Pin
webmangr9-Oct-06 2:41
webmangr9-Oct-06 2:41 
GeneralPositioning and Changing the beginning of the Week Pin
vanvank7-Sep-06 3:37
vanvank7-Sep-06 3:37 
AnswerRe: Positioning and Changing the beginning of the Week Pin
Massimo Beatini8-Sep-06 5:21
Massimo Beatini8-Sep-06 5:21 
Questionhow to display the day of the week and week number for given date Pin
janes7613-Jul-06 0:06
janes7613-Jul-06 0:06 
AnswerRe: how to display the day of the week and week number for given date Pin
Massimo Beatini13-Jul-06 5:56
Massimo Beatini13-Jul-06 5:56 
QuestionHide onclick out Pin
webmangr12-Jul-06 23:43
webmangr12-Jul-06 23:43 
AnswerRe: Hide onclick out Pin
Massimo Beatini14-Jul-06 4:54
Massimo Beatini14-Jul-06 4:54 
Questionhow to display the week number if the default start day for week is sunday Pin
happy_she2-Apr-06 21:16
happy_she2-Apr-06 21:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.