Criando DatePicker no Javascript

Você precisa estar logado para dar um feedback. Clique aqui para efetuar o login
Para efetuar o download você precisa estar logado. Clique aqui para efetuar o login
Confirmar voto
0
 (1)  (0)

Veja neste artigo como criar DatePicker no Javascript

Nesse artigo vou mostrar como podemos criar um DatePicker com Javascript.

Listagem 1: Criando estilo do componente


.borderButtonDatePicker
{
	border-right: #A0C0E7 1px solid; 
	border-top: #A0C0E7 1px solid;  
	border-left: #A0C0E7 1px solid;  
	border-bottom: #A0C0E7 1px solid;  
	background-color:#E2EBF5 ;       	
}
        
.borderTextBoxDatePicker
{
	border-top: #A0C0E7 1px solid;  
	border-left: #A0C0E7 1px solid;  
	border-bottom: #A0C0E7 1px solid;  
	background-color:#E2EBF5 ;       	
}        
        
.upButtonDatePicker
{          	          	
    height:10px;
	background: url(cal_plus.png) no-repeat center;	
}
        
.downButtonDatePicker
{         	
    height:10px;
	background: url(cal_minus.png) no-repeat center;	
}     
        
.fontDatePicker
{
	font-family:Segoe UI, Tahoma, Sans-Serif;
	font-size:10pt;
	color:#000000;	        	
}
        
.fontHeaderDatePicker
{
	font-family:Segoe UI, Tahoma, Sans-Serif;
	font-size:10pt;
	font-weight:bold;
	color:#1F3870;	        	
}   
        
.fontCellDatePicker
{
	font-family:Segoe UI, Tahoma, Sans-Serif;
	font-size:10pt;
	color:#000000;	        	
}               
        
.buttonDatePicker
{
	border-right: #A0C0E7 1px solid; 
	border-top: #A0C0E7 1px solid;  
	border-left: #A0C0E7 1px solid;  
	border-bottom: #A0C0E7 1px solid;  
	background-color:#E2EBF5 ; 
	font-family:Segoe UI, Tahoma, Sans-Serif;
	font-size:10pt;
	color:#000000;		              	
}        
        
.borderComboBoxDatePicker
{
	border-right: #A0C0E7 1px solid;  
	border-top: #A0C0E7 1px solid;  
	border-left: #A0C0E7 1px solid; 
	border-bottom: #A0C0E7 1px solid;
	background: -webkit-gradient(linear, left top, left bottom, from(#DFEEFF), to(#B4D4FF)); /* For Webkit Browsers */
	background: -moz-linear-gradient(top, #DFEEFF, #B4D4FF); /* for Firefox */
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#DFEEFF', endColorstr='#B4D4FF'); /* for IE */    
} 
        
.buttonComboBoxDatePicker
{
    border-left: #A0C0E7 1px solid; 
	border-right: #A0C0E7 1px solid; 
	border-top: #A0C0E7 1px solid;  
	border-bottom: #A0C0E7 1px solid;
	background-color: #E2EBF5;	
}

Listagem 2: Criando um enum para indicar se a lista do componente vai aparecer embaixo ou em cima


var AlignDatePicker = { ToUp: 0, ToDown: 1 };

Para criar o componente vamos criar uma classe no Javascript, abaixo vou explicar cada método da nossa classe.

Listagem 3: Construtor da classe


//Id = Nome do objeto
//alignPopup = Indicando se o popup aparece em cima ou embaixo.
function datePicker(id, alignPopup) {
    this.id = id;
    this.alignPopup = alignPopup;
    this.objMonth;
    this.objYear;

    this.currentDate;

    this.currentDay;

    this.lastObjDay;
    this.currentNameDay;

    this.corSelection;

    this.objDatePickerComboDIV = this.id + 'DatePickerComboDIV';
    this.objValueDatePicker = this.id + 'ValueDatePicker';
    this.objCalendarDatePickerDIV = this.id + 'CalendarDatePickerDIV';

    this.objNameLabelDatePicker = this.id + 'NameLabelDatePicker';
    this.objNameButtonDatePicker = this.id + 'NameButtonDatePicker';

    this.imgArrowComboBox = 'SetaCombo.png';

    this.onClick;
    this.onSelectionIndex;
}

Listagem 4: Métodos chamados quando os eventos onmouseover e onmouseout do combobox


datePicker.prototype.selectionComboBox = function () {
    var label = document.getElementById(this.objNameLabelDatePicker);
    var button = document.getElementById(this.objNameButtonDatePicker);

    button.style.backgroundColor = "#FFE6A0";

    label.style.borderBottomColor = "#FFCD4A";
    label.style.borderTopColor = "#FFCD4A";
    label.style.borderLeftColor = "#FFCD4A";
    label.style.borderRightColor = "#FFCD4A";

    button.style.borderBottomColor = "#FFCD4A";
    button.style.borderTopColor = "#FFCD4A";
    button.style.borderLeftColor = "#FFCD4A";
    button.style.borderRightColor = "#FFCD4A";
};

datePicker.prototype.deSelectionComboBox = function () {
    var label = document.getElementById(this.objNameLabelDatePicker);
    var button = document.getElementById(this.objNameButtonDatePicker);

    button.style.backgroundColor = "";

    label.style.borderBottomColor = "";
    label.style.borderTopColor = "";
    label.style.borderLeftColor = "";
    label.style.borderRightColor = "";

    button.style.borderBottomColor = "";
    button.style.borderTopColor = "";
    button.style.borderLeftColor = "";
    button.style.borderRightColor = "";
};
Combobox

Figura 1

Listagem 5: Métodos chamados quando os eventos onmouseover e onmouseout do botões para selecionar meses, anos


datePicker.prototype.selectionItem = function (elemento) {
    try {
        this.corSelection = elemento.style.backgroundColor;
        elemento.style.backgroundColor = "#FFE6A0";
    }
    catch (e) {
        alert(e.ToString());
    }
};

datePicker.prototype.deSelectionItem = function (elemento) {
    try {
        elemento.style.backgroundColor = this.corSelection;
    }
    catch (e) {
        alert(e.ToString());
    }
};
Combobox Meses

Figura 2

Listagem 6: Métodos para retornar os nomes dos meses e formatar


dateTimePicker.prototype.getMes = function (mes) {
    try {
        if (mes == 0) {
            return "Janeiro";
        }
        else if (mes == 1) {
            return "Fevereiro";
        }
        else if (mes == 2) {
            return "Março";
        }
        else if (mes == 3) {
            return "Abril";
        }
        else if (mes == 4) {
            return "Maio";
        }
        else if (mes == 5) {
            return "Junho";
        }
        else if (mes == 6) {
            return "Julho";
        }
        else if (mes == 7) {
            return "Agosto";
        }
        else if (mes == 8) {
            return "Setembro";
        }
        else if (mes == 9) {
            return "Outubro";
        }
        else if (mes == 10) {
            return "Novembro";
        }
        else if (mes == 11) {
            return "Dezembro";
        }
    }
    catch (e) {
        alert(e.ToString());
    }
};

dateTimePicker.prototype.formatNumberDateTime = function (value) {
    if (value.toString().length == 1) {
        return "0" + value;
    }
    else {
        return value;
    }
};

Listagem 7: Métodos para mostrar e esconde o popup


datePicker.prototype.showDivCombox = function () {
    try {
        var obj = document.getElementById(this.objDatePickerComboDIV);

        if (obj.style.display != 'block') {
            if (this.onClick != null) {
                this.onClick();
            }

            obj.style.display = 'block';

            if (this.alignPopup == AlignDatePicker.ToUp) {
                var objImg = document.getElementById('upImgPosition' + this.objNameButtonDatePicker);

                obj.style.top = (objImg.offsetTop - parseInt(obj.style.height) - 2) + 'px';
            }
            else {
                var objImg = document.getElementById('downImgPosition' + this.objNameButtonDatePicker);

                obj.style.top = (objImg.offsetTop + 2) + 'px';
            }
        }
        else {
            this.hideDivCombox();
        }
    }
    catch (e) {
        alert(e.ToString());
    }
};

datePicker.prototype.hideDivCombox = function () {
    try {
        document.getElementById(this.objDatePickerComboDIV).style.display = 'none';
    }
    catch (e) {
        alert(e.ToString());
    }
};
 

Listagem 8: Método chamado quando o cliente da um clique no botão ok, data e hora são colocadas no label


datePicker.prototype.selectionValueDateTimePicher = function () {
    try {
        this.setValueTextBox();

        document.getElementById(this.objDatePickerComboDIV).style.display = 'none';

        if (this.onSelectionIndex != null) {
            this.onSelectionIndex();
        }
    }
    catch (e) {
        alert(e.ToString());
    }
};

Listagem 9: Método para selecionar o dia

datePicker.prototype.selectionDayDatePicker = function (objDay) {
    try {
        if (this.lastObjDay != null) {
            this.lastObjDay.bgColor = '';
        }
        else {
            document.getElementById(this.currentNameDay).bgColor = '';
        }

        this.lastObjDay = objDay;
        this.lastObjDay.bgColor = '#FFE6A0';

        this.currentDay = this.lastObjDay.innerHTML;

        this.selectionValueDateTimePicher();
        this.hideDivCombox();
    }
    catch (e) {
        alert(e.ToString());
    }
};
Combobox Dia

Figura 3

Listagem 10: Métodos para retornar a data selecionada


datePicker.prototype.getDate = function () {
    return new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), this.currentDay);
};

Listagem 11: Métodos colocar uma nova data

datePicker.prototype.setNewDate = function (newDate) {
    this.currentDate = newDate;

    this.currentDay = this.currentDate.getDate();

    this.createCalendarDatePicker();

    this.setValueTextBox();
};

Listagem 12: Método para colocar a data na label


datePicker.prototype.setValueTextBox = function () {
    document.getElementById(this.objValueDatePicker).innerHTML = this.formatNumberDateTime(this.currentDay) + '/' + this.formatNumberDateTime(this.currentDate.getMonth() + 1) + '/' + 
this.currentDate.getFullYear();
}

Listagem 13: Método para inicializar o componente


datePicker.prototype.onLoadDatePicker = function (valueDate, objRecipient, valueWidth) {
    try {
        this.currentDate = valueDate;

        this.currentDay = this.currentDate.getDate();

        objRecipient.innerHTML = this.createComboBoxDatePicker(valueWidth);

        this.objMonth = document.getElementById('month' + this.id);
        this.objYear = document.getElementById('year' + this.id);

        this.updateDateDatePicker();

        this.setValueTextBox();
    }
    catch (e) {
        alert(e.ToString());
    }
};

Listagem 14: Métodos para alterar mês, ano


datePicker.prototype.onClickUpMonthDatePicker = function () {
    this.currentDate.setMonth(this.currentDate.getMonth() - 1);
    this.updateDateDatePicker();

    this.createCalendarDatePicker();
};

datePicker.prototype.onClickDownMonthDatePicker = function () {
    this.currentDate.setMonth(this.currentDate.getMonth() + 1);
    this.updateDateDatePicker();

    this.createCalendarDatePicker();
};

datePicker.prototype.onClickUpYearDatePicker = function () {
    this.currentDate.setYear(this.currentDate.getFullYear() - 1);
    this.updateDateDatePicker();

    this.createCalendarDatePicker();
};

datePicker.prototype.onClickDownYearDatePicker = function () {
    this.currentDate.setYear(this.currentDate.getFullYear() + 1);
    this.updateDateDatePicker();

    this.createCalendarDatePicker();
};

datePicker.prototype.updateDateDatePicker = function () {
    try {
        this.objMonth.innerHTML = this.getMes(this.currentDate.getMonth());
        this.objYear.innerHTML = this.currentDate.getFullYear();
    }
    catch (e) {
        alert(e.ToString());
    }
};

Listagem 15: Métodos para criar o Combo e o calendário

//Cria o combobox.
datePicker.prototype.createComboBoxDatePicker = function (valueWidth) {
    var tableComboBox = '';

    tableComboBox += '<table cellpadding="0" cellspacing="0" border="0" width="' + (parseInt(valueWidth) + 10) + 'px"> \r\n';
    tableComboBox += '    <tr> \r\n ';
    tableComboBox += '        <td id="' + this.objNameLabelDatePicker + '" style="width:' + valueWidth + 'px;" class="borderButtonDatePicker" onmouseover="' + this.id + '.selectionComboBox();" onmouseout="' 
+ this.id + '.deSelectionComboBox();"> \r\n ';
    tableComboBox += '            <img id="upImgPosition' + this.objNameButtonDatePicker + '" style="position:absolute;visibility:hidden;" alt="" src="' + this.imgArrowComboBox + '" />  \r\n';
    tableComboBox += '             <label id="' + this.objValueDatePicker + '" class="fontDatePicker" style="width:100%"> </label> \r\n ';
    tableComboBox += '        </td> \r\n ';
    tableComboBox += '        <td id="' + this.objNameButtonDatePicker + '"  style="width:10px;" align="center" class="buttonComboBoxDatePicker" onclick="' + this.id + '.showDivCombox();" onmouseover="' + 
this.id + '.selectionComboBox();" onmouseout="' + this.id + '.deSelectionComboBox();" > \r\n ';
    tableComboBox += '            <img id="img' + this.objNameButtonDatePicker + '" alt="" src="' + this.imgArrowComboBox + '" />  \r\n';
    tableComboBox += '        </td>  \r\n';
    tableComboBox += '    </tr> \r\n ';
    tableComboBox += '    <tr> \r\n ';
    tableComboBox += '        <td> \r\n ';
    tableComboBox += '            <img id="downImgPosition' + this.objNameButtonDatePicker + '" style="position:absolute;visibility:hidden;" alt="" src="' + this.imgArrowComboBox + '" />  \r\n';
    tableComboBox += '            <div id="' + this.objDatePickerComboDIV + '" style="position:absolute;width:200px;height:145px;display:none;overflow:hidden;top:0;" class="borderComboBoxDatePicker"> ';
    tableComboBox += '              ' + this.createTableDatePicker();
    tableComboBox += '            </div> \r\n ';
    tableComboBox += '        </td>  \r\n';
    tableComboBox += '    </tr> \r\n ';
    tableComboBox += '</table> \r\n ';

    return tableComboBox;
};

//Cria a estrutura.
datePicker.prototype.createTableDatePicker = function () {
    var content = '';

    content += '<table cellspacing="0" cellpadding="0" border="0" width="180px" align="center">';
    content += '    <tr style="height:3px;" ><td></td></tr>';
    content += '    <tr>';
    content += '        <td style="width:90px;">';
    content += '            <table cellspacing="0" cellpadding="0" border="0" width="90px">';
    content += '                <tr>';
    content += '                    <td style="width:75px" class="borderTextBoxDatePicker">';
    content += '                         <label id="month' + this.id + '" class="fontDatePicker"> </label>';
    content += '                    </td>';
    content += '                    <td style="width:15px;">';
    content += '                        <table cellspacing="0" cellpadding="0" border="0" width="100%" class="borderButtonDatePicker">';
    content += '                            <tr>';
    content += '                                <td class="upButtonDatePicker" onclick="' + this.id + '.onClickUpMonthDatePicker();" onmouseover="' + this.id + '.selectionItem(this);" onmouseout="' + this.id + 
'.deSelectionItem(this);">';
    content += '                        ';
    content += '                                </td>';
    content += '                            </tr>';
    content += '                            <tr>';
    content += '                                <td class="downButtonDatePicker" onclick="' + this.id + '.onClickDownMonthDatePicker();" onmouseover="' + this.id + '.selectionItem(this);" onmouseout="' + this.id + 
'.deSelectionItem(this);">';
    content += '                ';
    content += '                                </td>';
    content += '                            </tr>';
    content += '                            </table>';
    content += '                    </td>';
    content += '                </tr>';
    content += '            </table>';
    content += '        </td>';
    content += '        <td style="width:20px;"></td>';
    content += '        <td style="width:70px;">';
    content += '            <table cellspacing="0" cellpadding="0" border="0" width="70px">';
    content += '                <tr>';
    content += '                    <td style="width:55px" class="borderTextBoxDatePicker">';
    content += '                         <label id="year' + this.id + '" class="fontDatePicker"> </label>';
    content += '                    </td>';
    content += '                    <td style="width:15px;">';
    content += '                        <table cellspacing="0" cellpadding="0" border="0" width="100%" class="borderButtonDatePicker">';
    content += '                            <tr>';
    content += '                                <td class="upButtonDatePicker" onclick="' + this.id + '.onClickUpYearDatePicker();" onmouseover="' + this.id + '.selectionItem(this);" onmouseout="' + this.id + 
'.deSelectionItem(this);">';
    content += '                        ';
    content += '                                </td>';
    content += '                            </tr>';
    content += '                            <tr>';
    content += '                                <td class="downButtonDatePicker" onclick="' + this.id + '.onClickDownYearDatePicker();" onmouseover="' + this.id + '.selectionItem(this);" onmouseout="' + this.id + 
'.deSelectionItem(this);">';
    content += '                ';
    content += '                                </td>';
    content += '                            </tr>';
    content += '                            </table>';
    content += '                    </td>';
    content += '                </tr>';
    content += '            </table>';
    content += '        </td>';
    content += '    </tr>';
    content += '    <tr style="height:7px;" ><td></td></tr>';
    content += '    <tr>';
    content += '        <td colspan="3">';
    content += '            <div id="' + this.objCalendarDatePickerDIV + '" style="width:180px;">';
    content += '            ' + this.createCalendarDatePicker(true);
    content += '            </div>';
    content += '        </td>';
    content += '    </tr>';
    content += '    <tr style="height:7px;" ><td></td></tr>';
    content += '</table>';

    return content;
};

//Cria o calendario.
datePicker.prototype.createCalendarDatePicker = function (isReturn) {
    try {
        var date = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), 1);

        this.lastObjDay = null;
        this.currentNameDay = '';

        var table = '<table cellpadding="0" cellspacing="0" border="0" width="100%" class="borderButtonDatePicker">\r\n';

        for (var i = 0; i < 6; i++) {
            table += '  <tr>\r\n';

            var columns = [' ', ' ', ' ', ' ', ' ', ' ', ' '];

            if (i > 0) {
                var isNextTr = false;

                for (var iCol = 0; iCol < columns.length; iCol++) {
                    if (!isNextTr) {
                        var day = date.getDate();

                        if (day == 1 && i > 1) {
                            isNextTr = true;
                            continue;
                        }

                        columns[date.getDay()] = day;

                        date.setDate(day + 1);

                        if (date.getDate() == day) {
                            date.setDate(day + 1);
                        }

                        if (date.getDay() == 0) {
                            isNextTr = true;
                        }
                    }
                }
            }
            else {
                columns = ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'];
            }

            for (var iCol = 0; iCol < columns.length; iCol++) {
                var styleCol = '';
                var cursorCol = '';
                var bgColorCol = '';
                var onClickCol = '';

                if (i > 0 && iCol < columns.length - 1) {
                    styleCol = 'border-right: #A0C0E7 1px solid;';
                }

                if (i == 1) {
                    styleCol += 'border-top: #A0C0E7 1px solid;';
                }

                if (columns[iCol] == this.currentDay) {
                    bgColorCol = 'bgColor="#FFE6A0"';
                    this.currentNameDay = this.id + 'currentObjDatDatePicker';
                }

                if (i > 0 && columns[iCol] != ' ') {
                    cursorCol = 'cursor:pointer;';
                    onClickCol = 'onclick="' + this.id + '.selectionDayDatePicker(this);"';
                }

                table += '      <td id="' + this.currentNameDay + '" ' + onClickCol + ' ' + bgColorCol + ' style="' + cursorCol + styleCol + '" align="center" class="' + (i == 0 ? 'fontHeaderDatePicker' : 
'fontCellDatePicker') + '">' + columns[iCol] + '</td>';
            }

            table += '  </tr>\r\n';
        }

        table += '</table>\r\n';

        if (isReturn == null || isReturn == false) {
            document.getElementById(this.objCalendarDatePickerDIV).innerHTML = table;
        }
        else {
            return table;
        }
    }
    catch (e) {
        alert(e.ToString());
    }
}; 

Listagem 16: Vamos criar agora o HTML

<html>
<head>
    <title>DateTimePicker</title>
    <link rel="stylesheet" href="MainStyleSheet.css" type="text/css" />
    <script language="javascript" type="text/javascript" src="DatePickerJScript.js"></script>
    <script language="javascript" type="text/javascript">
    var oDatePicker;

    function onLoadDatePicker() {
        oDatePicker = new datePicker('oDatePicker', AlignDatePicker.ToDown);

        oDatePicker.onLoadDatePicker(new Date(), document.getElementById('recipientDatePicker'), 130);
    }
    </script>
</head>
<body onload="onLoadDatePicker();">
<table cellpadding="0" cellspacing="0" border="0" width="150px">
    <tr>
        <td id="recipientDatePicker">
            
        </td>
    </tr>
</table>
</body>
</html>
Combobox HTML

Figura 4

Até o próximo artigo.

 
Você precisa estar logado para dar um feedback. Clique aqui para efetuar o login
Receba nossas novidades
Ficou com alguma dúvida?