본문 바로가기
Web/Tistory

[JS] 티스토리 달력 위젯 만들기

by r4bb1t 2020. 5. 14.
반응형

결과물

티스토리 사이드바에 무엇을 넣으면 좋을까 하다가, 간단한 달력이 있으면 좋을 것 같아서 만들어 보았다.


Date를 이용해 월별 달력 배열 만들기 |

let today = new Date();
let final = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (today.getFullYear() % 4 == 0 && (today.getFullYear() % 100 != 0 || today.getFullYear() % 400 == 0)) {
  final = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
}
function prev() {
  today = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
  makeArray();
}
function next() {
  today = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate());
  makeArray();
}
function makeArray() {
  let first = new Date(today.getFullYear(), today.getMonth(), 1);
  let day = 1;
  let cal = new Array(6);
  cal.fill(" ");
  let j = first.getDay();
  for (let i = 0; i < 6; i++) {
    cal[i] = new Array(7);
    cal[i].fill(" ");
    for (j; j < 7; j++) {
      cal[i][j] = day++;
      if (day > final[today.getMonth()] + 1) cal[i][j] = " ";
    }
    j = 0;
  }
  arrayToTable(cal);
}

today에는 달력을 표시할 기준이 되는 날짜를, final에는 윤년을 체크해서 각 월 별 마지막 날짜를 넣었다.

prev(), next() 함수는 각각 이전 달, 다음 달 버튼을 눌렀을 때 실행될 함수로, 기준점을 한달 전 / 후로 바꿔주고 캘린더를 업데이트한다.

makeArray()가 캘린더를 업데이트하는 함수인데, first에는 기준 달의 첫째 날을 넣어놓았다.

다음 부분은 cal 배열을 공백으로 초기화하고, 각 달의 마지막 날(final)까지 배열을 채워준다.

그 후 만들어진 배열을 HTML table 안에 넣어주는 함수 arrayToTable(cal)를 실행해준다.


JS 배열을 HTML table에 넣기 |

function arrayToTable(arr) {
  document.getElementById("monthTable").innerHTML =
    "<span>" +
    today.getFullYear() +
    "</span> " +
    "<span style='font-weight:800; color:'>" +
    (today.getMonth() < 9 ? "0" + (((today.getMonth() - 1) % 12) + 2) : ((today.getMonth() - 1) % 12) + 2) +
    "</span> ";
  let calendar = document.getElementById("calendar").getElementsByTagName("tbody")[0];
  if (calendar.rows.length > 2)
    for (let i = 0; i < 6; i++) {
      calendar.deleteRow(-1);
    }
  for (let i = 0; i < 6; i++) {
    let row = calendar.insertRow();
    for (let j = 0; j < 7; j++) {
      cell = row.insertCell();
      if (arr[i][j] != undefined) {
        if (today.getMonth() == new Date().getMonth() && today.getFullYear() == new Date().getFullYear() && arr[i][j] == today.getDate()) {
          cell.innerHTML = '<span style="color:; font-weight:700;">' + arr[i][j] + "</span>";
        } else {
          cell.innerHTML = arr[i][j];
        }
      }
    }
  }
}

arr을 입력받아 table에 넣어주는 함수이다.

monthTable 부분은 2020 05 처럼 현재 년월을 표시해주는 테이블 헤더 부분인데, 티스토리에 설정해둔 컬러 치환자와 font-weight를 이용해 포인트를 주었다.

월 부분은 한자리수이면 앞에 0을 붙여 두자리로 표현하게 했다.

let calendar = document.getElementById("calendar").getElementsByTagName("tbody")[0]; 로 calander의 tbody를 가져와, 작업을 진행한다.

만약 calender.rows.length 즉 줄이 있다면 원래 있던 달력 부분을 지워준다. 맨 처음 달력을 표시할 땐 rows가 비어있기 때문에 그냥 지워버리면 오류가 나기 때문에 체크해준다.

이중 for문으로 각 행마다 calendar에 row를 새로 만들어주고, 각 열마다 row에 cell을 만들어준다.

cell 안에는 innerHTML로 그 칸에 맞는 날짜를 넣어주는데, '오늘'을 강조하기 위해 기준 년월이 현재와 동일하고 해당 날짜가 오늘의 date와 일치하면 위에서와 같이 컬러 치환자와 font-weight로 포인트를 주었다.

jQuery를 이용하면 조금 더 깔끔한 코드를 짤 수 있을 것이다.


HTML 테이블 |

<widget class="no-drag">
  <table id="calendar">
    <thead>
      <tr height="35px">
        <td><label onclick="prev()" style="color: #ccc;"><</label></td>
        <td colspan="5" id="monthTable"></td>
        <td><label onclick="next()" style="color: #ccc;">></label></td>
      </tr>
      <tr id="dateHead">
        <td>S</td>
        <td>M</td>
        <td>T</td>
        <td>W</td>
        <td>T</td>
        <td>F</td>
        <td>S</td>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <script>
    makeArray();
  </script>
</widget>

widget class에 no-drag를 넣어 CSS로 나중에 위젯 내 글자가 드래그되는 것을 막아줄 것이다.

thead 안에는 아까 만들어둔 prev()와 next()를 실행시켜줄 라벨 버튼을 넣어준다. 두 라벨의 가운데에는 기준 년월을 받아올 monthTable이 있을 것이다.

그 아래 dateHead는 그냥 요일을 표시해주는 행이다. 아이디는 CSS 조정을 하려고 넣었다.

tbody 안의 내용은 JS에서 채우므로 비워둔다.

그리고 최초에 달력을 채우기 위해 makeArray()를 실행시켜준다.


CSS |

.no-drag {-ms-user-select: none; -moz-user-select: -moz-none; -webkit-user-select: none; -khtml-user-select: none; user-select:none;}

#calendar {
	text-align: center;
}
#calendar thead {
	font-size: 16px;
	font-weight: 700;
	text-align: center;
}
#calendar td {
	text-align: center;
}
#calendar tbody td {
	width: 10px;
	height: 10px;
	padding: 5px;
	font-size: 12px;
	font-weight: 400;
}
#dateHead {
	font-size: 12px;
	font-weight: 700;
	text-align: center;
}

css는 그냥 넣어주면 된다.


티스토리 스킨에 넣을 때는 JS구문을 <script type="text/javascript"></script> 태그로 넣으면 된다.

나는 사이드바에 넣었는데, 다른 곳에 넣어도 무방하다. 또 어떤 기능을 추가하면 재밌을지 생각해봐야겠다.

 

+ 찾아보니 티스토리 기본 모듈에 달력이 있다🙄.. 여러분 그냥 기본 모듈 CSS 수정해서 쓰세요. 나는 그냥 코딩연습한걸로..

반응형

'Web > Tistory' 카테고리의 다른 글

[HTML] 티스토리 사이드바에 프로필 넣기  (11) 2021.02.27
[CSS] 스크롤바 커스텀하기  (0) 2020.08.05
[CSS] 티스토리 스킨 커서 바꾸기  (1) 2020.05.07

댓글