dom제어 기초(inline vs script태그)+toggle
본문 바로가기

Frontend/dom

dom제어 기초(inline vs script태그)+toggle

 

www.w3schools.com/howto/howto_js_toggle_dark_mode.asp

 

How To Toggle Between Dark and Light Mode

How TO - Toggle Dark Mode Switch between dark and light mode with CSS and JavaScript. Try it Yourself » Toggle Class Step 1) Add HTML: Use any element that should store the content you want to toggle the design for. In our example, we will use for the sak

www.w3schools.com

inline방식

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트를 통해 html을 제어해보자</title>
    <style>
        #selected{
            color:red;
        }
        .dark{
            background-color: black;
            color:white
        }
        .dark #selected{
            color:yellow
        }
    </style>
    <!-- <script>
        function darkBackground(){
            document.body.classList.toggle("dark")
        }
    </script> -->
</head>
<!-- <body class="dark"> -->
<body class="">
    <ul>
        <li>HTML</li>
        <li>CSS</li>
        <li id="selected">Javascript</li>
        <!-- <input type="button" value="어두운배경버튼" onclick="darkBackground()"> -->
        <input type="button" value="darkbtn" onclick="document.body.classList.toggle('dark');">
    </ul>
</body>
</html>

body를 선택하고싶을땐

document.body

 

document.body.classList("dark")

문서에 body태그안에 dark라는 클래스를 넣겠다~

 

클래스명을 변경+토글하고싶을때

document.body.classList.toggle("클래스명")

 

html은 정보이고 javascript는 제어인데 inline으로 같이 나타낼경우 유지보수가 어려움 -> 분리권장(script태그)

 

script태그

 

주의할점! body태그안 하단에 위치하지않을경우

Cannot read property 'addEventListener' of null

이라는 오류메시지 출력하기때문에 script태그 위치주의

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트를 통해 html을 제어해보자(script태그)</title>
    <style>
        #selected{
            color:red;
        }
        .dark{
            background-color: black;
            color:white
        }
        .dark #selected{
            color:yellow
        }
    </style>

</head>
<!-- <body class="dark"> -->
<body class="">
    <ul>
        <li>HTML</li>
        <li>CSS</li>
        <li id="selected">Javascript</li>
        <!-- <input type="button" value="어두운배경버튼" onclick="darkBackground()"> -->
        <input type="button" value="darkbtn" id="darkbtn">
    </ul>
    <script>
        var darkbtn = document.querySelector('#darkbtn')
        darkbtn.addEventListener('click', () => {
            document.body.classList.toggle('dark')
        });
    </script>
</body>
</html>

 

head태그 안에위치하고싶다면?

1. onload매소드 호출(가급적 바디태그 뒤에다가하는것이 바람직)

window.onload=function(){

};

2.defer, async공부~

ko.javascript.info/script-async-defer

 

defer, async 스크립트

 

ko.javascript.info

 

반응형