JavaScript

JS | clock(digital) , add back to top button

3jun 2021. 12. 17. 19:48

clock (digital)

#html
<div class="clock">
     <h1>00:00</h1>
</div>

--------------------------------------------------------
#js
const clock = document.querySelector(".clock");
const clockTitle = clock.querySelector("h1");

function getTime() {
    const date = new Date();

    const hours  date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    clockTitle.innerText = 
        `${hours < 10 ? `0${hours}`:hours} : 
        ${minutes < 10 ? `0${minutes}` : minutes} : 
        ${seconds < 10 ? `0${seconds}` : seconds}`;
}

function initClock() {
    getTime();
    setInterval(getTime, 1000);
}

initClock();

clock (digital) 구조

  1. date 상수에 new Date() 함수를 사용하여 현재 시간을 할당한다.
  2. date 상수를 사용하여 hours, minutes, seconds 상수에 시간, 분, 초를 나누어 할당한다.
  3. 시간이 표시될 h1 태그에 innerText를 이용하여 현재 시간을 표시하는데, 이때 조건문과 백틱을 조합하여 원하는 포맷으로 표시되게 한다.
  4. 여기까지 작성된 getTime 함수를 실행하기 위해 initClock 이라는 trigger 함수를 생성한 후, web API인 setInterval을 사용하여 매초 단위로 initClock이 실행 되도록 한다.
  5. 특별한 trigger가 없어도 initClock이 실행될 수 있도록 initClock() 함수를 호출한다.

add back to top button

페이지 우측 하단에 클릭을 하면 맨 위로 이동하는 add back to top button 을 생성하고 이 button은 화면을 아래로 어느 정도 scroll 했을 때 나타날 수 있도록 한다.

#html
<button class="arrowUp invisible">
     <span>Back to TOP</span>
     <i class="far fa-arrow-alt-circle-up"></i>
</button>

#js
const arrowUp = document.querySelector(".arrowUp");
const backToTop = document.getElementById("greeting");
document.addEventListener("scroll", () => {
    const currentHeight = window.scrollY
    console.log(currentHeight);

    if (currentHeight < 450 ){
        arrowUp.classList.add("invisible");
        arrowUp.style.pointerEvents = "none";
    } else {
        arrowUp.classList.remove("invisible");
        arrowUp.style.pointerEvents = "auto";
    }
});

arrowUp.addEventListener('click', () => {
    backToTop.scrollIntoView();
});

add back to top button 구조

  1. 버튼을 클릭하면 이동할 element 할당 (backToTop 상수)
  2. 페이지에서 scroll 이 발생하면 scroll 된 현재 위치를 currentHeight 상수에 할당
  3. 현재 페이지를 넘어가는 scroll 위치인 450을 넘어가면 버튼을 감추는 invisible class가 제거되고, 450을 넘어가지 않으면 invisible class가 추가되어 버튼이 안보이도록 한다.
  4. 버튼이 없을 때는 해당 위치에 커서가 올라가도 pointer가 나타나면 안되므로
    element.style.pointerEvents 속성 값을 none으로 한다.