Week 4 - 자기소개 홈페이지 나이트모드 버튼 추가 | JavaScript

grl pwr·2022년 5월 16일
0

🌈 나이트모드 기능을 개인 웹사이트에 추가해보자


day mode가 디폴트 값이고 toggle 버튼을 누르면 나이트 모드 작동

  1. Visual Studio Code에서 extensions 메뉴에 들어가 font awesome auto-complete & preview를 install 한다

  1. fontawesome의 아이콘을 사용하기 위해 아래 링크를 html head 태그에 넣어준다
<!-- day & night mode button -->
    <link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
</head>
  1. body 태그 안에 체크박스 만들기
<div>
   <input type="checkbox" class="checkbox" id="checkbox">
      <label for="checkbox" class="label">
         <i class="fas fa-sun"></i>
         <i class="fas fa-moon"></i>
         <div class="ball"></div>
      </label>
</div>
/* day / night mode button */

body.dark {
    background-color: #292c35;
    transition: background 0.2s linear;
}

body.dark a {
    color: #fff;
}

.checkbox {
    opacity: 0;
    position: absolute;
    float: right;
}

.label {
    background-color: #111;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 50px;
    position: relative;
    padding: 5px;
    height: 26px;
    width: 50px;
}

.ball {
    background-color: #fff;
    border-radius: 50%;
    position: absolute;
    top: 2px;
    left: 2px;
    height: 22px;
    width: 22px;
    transition: transform 0.2s linear;
}

.checkbox:checked + .label .ball {
    transform: translateX(24px);
}

.fa-sun {
    color: #f39c12;
}

.fa-moon {
    color: #f1c40f;
}
// day & night mode button

const checkbox = document.getElementById('checkbox');
checkbox.addEventListener('change', () => {
    //change the theme of the website
    document.body.classList.toggle('dark');
});

🎯 document.getElementById(id);

🎯 EventTarget.addEventListener()

메서드는 지정한 유형의 이벤트를 대상이 수신할 때마다 호출할 함수를 설정합니다.

일반적인 대상은 Element, Document, Window가 있습니다.

profile
4대륙 개발자

0개의 댓글