Get current day
In JavaScript, to get the current day you use the method getDate()
:
var hoje = new Date().getDate();
Get the week indicated
To get the week indicated in JavaScript, during the construction of the table rows, we can check when opening a new <tr/>
if it is the week we want to highlight:
// ...
var weekNum=0;
// ...
if (d.getDay() % 7 == 6) {
// a variavel de controlo a ser incrementada
weekNum++;
// se for igual à semana indicada, aplicar classe de CSS
if (weekNum == highlightWeek) {
table.push('</tr><tr class="highlightWeek">');
}
else {
table.push('</tr><tr>');
}
}
// ...
Example
Your code can then look like this:
function Calendar(id, year, month, highlightWeek) {
var elem = document.getElementById(id),
mon = month - 1,
d = new Date(year, mon),
today = new Date().getDate();
var weekDay = ["Sun", "Mon", "Tues", "Wed", "Thu", "Fri", "Sat"];
var months = ['January', 'Frebruary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var table = ['<table><tr>']
table.push('<th colspan = 4>' + months[mon] + '</th>' + '<th colspan = 3>' + year + '</th>' + '</tr><tr>')
for (var i = 0; i <= 6; i++ ) {
table.push('<th>' + weekDay[i] + '</th>');
}
table.push('</tr><tr>')
for (var i=0; i<d.getDay(); i++) {
table.push('<td></td>')
}
var weekNum = 1;
while (d.getMonth() == mon) {
var tdClass1 = today==d.getDate() ? 'curDay' : '';
table.push('<td class="'+tdClass1+'">'+d.getDate()+'</td>');
if (d.getDay() % 7 == 6) {
weekNum++;
if (weekNum == highlightWeek) {
table.push('</tr><tr class="highlightWeek">');
}
else {
table.push('</tr><tr>');
}
}
d.setDate(d.getDate()+1);
}
for (var i=d.getDay(); i<7; i++) {
table.push('<td></td>')
}
table.push('</tr></table>')
elem.innerHTML = table.join('\n')
}
new Calendar("cal", 2015, 3, 2);
.curDay {
font-weight:bold;
}
.highlightWeek{
background-color:pink;
}
<div id='cal'></div>
The above example is also available on JSFiddle .