Advertisement
braveheart1989

calendar

Oct 23rd, 2016
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. function calendar([day, month, year]) {
  2. const monthNames = ["January", "February", "March", "April", "May", "June",
  3. "July", "August", "September", "October", "November", "December"
  4. ];
  5. const shortMonthNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  6. month = month - 1;
  7.  
  8. let container = $('#content');
  9. let date = new Date();
  10. date.setFullYear(year, month);
  11. date.setDate(1);
  12. let table = $('<table></table>');
  13. let tBody = $('<tbody></tbody>');
  14.  
  15. //
  16. // table header
  17. //
  18.  
  19. $(`<caption>${monthNames[date.getMonth()]} ${date.getFullYear()}</caption>`).appendTo(table);
  20. let trHeaders = $('<tr></tr>');
  21. shortMonthNames.forEach(dayOfWeek => {
  22. $(`<th>${dayOfWeek}</th>`).appendTo(trHeaders);
  23. });
  24. trHeaders.appendTo(table);
  25.  
  26. //
  27. // table body
  28. //
  29.  
  30. // empty days on the front
  31. let emptyCellsToAdd = date.getDay() == 0 ? 6 : date.getDay() - 1;
  32. let emptyTrFront = $('<tr></tr>');
  33. for (let i = 0; i < emptyCellsToAdd; i++) {
  34.  
  35. $('<td></td>').appendTo(emptyTrFront);
  36. }
  37.  
  38.  
  39. //IF CLAUSE ADDED! ONLY IF EMPTY CELLS !=0 ADD <tr>
  40. if (emptyCellsToAdd!=0) {
  41. for (let i = 0; i < 7-emptyCellsToAdd; i++) {
  42.  
  43. //CHECK IF TODAY! OTHERWISE IF TODAY IS ON THE FIRST ROW, IT DOES NOT GET CLASS="TODAY"
  44. if (date.getDate() == day)
  45. $(`<td class="today">${date.getDate()}</td>`).appendTo(emptyTrFront);
  46. else
  47. $(`<td>${date.getDate()}</td>`).appendTo(emptyTrFront);
  48.  
  49.  
  50. date.setDate(date.getDate() + 1);
  51. }
  52. emptyTrFront.appendTo(tBody);
  53. }
  54.  
  55.  
  56. // cells with dates
  57. let trMonthDays = $('<tr></tr>');
  58. let index = 0;
  59. while (date.getMonth() == month) {
  60. // create new row
  61.  
  62.  
  63. //ADDED ANOTHER CHECK. IF INDEX IS 0 DO NOT APPEND EMPTY ROW!
  64. if (index % 7 == 0 && index!=0) {
  65. trMonthDays.appendTo(tBody);
  66. trMonthDays = $('<tr></tr>');
  67.  
  68. }
  69. if (date.getDate() == day)
  70. $(`<td class="today">${date.getDate()}</td>`).appendTo(trMonthDays);
  71. else
  72. $(`<td>${date.getDate()}</td>`).appendTo(trMonthDays);
  73. // step
  74. date.setDate(date.getDate() + 1);
  75. index++;
  76. }
  77. date.setDate(date.getDate() - 1);
  78.  
  79. // empty days on the back
  80. if (date.getDay() != 0) {
  81. for (let i = 0; i < 7 - date.getDay(); i++) {
  82. $('<td></td>').appendTo(trMonthDays);
  83. }
  84. }
  85. trMonthDays.appendTo(tBody);
  86. tBody.appendTo(table);
  87. table.appendTo(container);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement