본문 바로가기

Javascript

function과 event로 웹페이지 배경색을 바꾸기

강의를 보고 button click event로 웹페이지의 배경색을 바꿔보았다

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" a href="style.css">
    <script defer src="app.js"></script>
</head>
<body>
    <h1>WEB</h1>
    <input type="button" id="night_day" onclick="nightDayHandler(this);" value="night"> <!--this를 넣어서 javascript function을 알려줘야함-->
</body>
</html>

 

 

'use strict';

//const btn = document.getElementById('nightDay'); 이건 소용이 없네..

function nightDayHandler(self) {
    const target = document.querySelector('body');
    if(self.value === 'night') { //이 값이 night라면 black모드에 yellow 글자에 day btn이 있어야한다 
        target.style.backgroundColor = "black";
        target.style.color = "Yellow";
        self.value = "day"; //black 모드일 때, 버튼 이름은 day를 보여줘야하니까
    }else {
        target.style.backgroundColor = "Yellow";
        target.style.color = "black";
        self.value = "night";
    }
}

nightDay.addEventListener("click", nightDayHandler);
//nightDayHandler가 실행될 때, this의 값을 html에 input을 가르키기 위해서 input onclick에도 넣어서 알려줘야한다
//input의 this라는게 javascript의 매개변수 self로 들어와서 this로 바꾼다.