노마드코더 실습 코드 (3강)

yiseonline·2023년 5월 6일
0

nomadCoder

목록 보기
2/8
post-thumbnail

3.0 The Document Object


ㄴ 이거 처럼 js는 자동으로 html과 연결되어있다 !!

ㄴ js는 연결되어있어서 여기서 막 제목도 바꾸고 그럴 수 있음
html에서 많은 것을 가져올 수 있고 javascript로 그것들을 볼 수 있음


3.1 HTML in Javascript


ㄴ 왜 null 나오냐 킹받게 !!!

헤헤 나옴

title.innerText="got you!" 이렇게 하면 js에 의해 제목이 변경됨

-last code-

const title=document.getElementById("title"); //html에서 title 받아오고
//getElementById (function) = find element through id from html

console.dir(title); //이건 무슨 코드일까 dir 요거
title.innerText="got you!" //change title

console.log(title.id); //log id
console.log(title.className);// log className

3.2 Searching For Elements

caught TypeError: Cannot set properties of null (setting 'innerText')
    at app.js:5:16

ㄴ 에러 = null 의 innerText에 접근하려 한 것

title이 null 인데 접근하려해서 에러가 뜬다 ~

const hellos=document.getElementsByClassName("hello");
//array that has many 'h1's
// elements를 가져오는 방법

console.log(hellos);
const title = document.querySelector(".hello h1");
// ㄴ hello라는 class 내부에 있는 g1을 가지고 올 수 있다는거
// querySelector = search for element using css method / only return one element (first one!)

//다 가져오고 싶으면 querySelectorAll을 써야함
console.log(title);
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="style.css">
        <title>Momentum App</title>
    </head>
    <body>
        <div class = "hello">
        <h1>Grab me!1</h1>
        </div>

        <div class = "hello">
            <h1>Grab me!2</h1>
            </div>

        <div class = "hello">
            <h1>Grab me!3</h1>
            </div>
        <script src="app.js"></script>
    </body>
</html>
const title=document.querySelector("#hello");
const title = document.getElementById("hello");

ㄴ 이 둘은 같은 거지만 하나만 받아오고 싶을 때는 getElementById 로 할 수 없당


3.3 Events


대체 뭐가 문제인 것이냐.. 똑같은데 !!!

... 해결함 first-child입니다.. chile이 아니라!!!

-last code-

const title = document.querySelector("div.hello:first-child h1");

function handleTitleClick()
{
    title.style.color="blue"; //click -> change color
    console.log("title was clicked!");
}

title.addEventListener("click",handleTitleClick); //괄호를 안넣는다! 
//왜? js에게 함수 넘겨주고 js가 알아서 실행시킬거기 때문
//js가 title을 지켜보고 있다가 click하는 것을 listen할 것임
//click 하면 handleTitleClick 함수가 작동하길 원함
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="style.css">
        <title>Momentum App</title>
    </head>
    <body>
        <div class = "hello">
        <h1>Grab me!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

3.4 Events part Two

마우스가 우리의 title 위에 올라갈 때, click은 하지 않고 그냥 위에 위치할 때의 event
= mouseenter

//mouseEnter function
function handleMouseEnter()
{
    console.log("mouse is here!");
}

title.addEventListener("mouseenter",handleMouseEnter);

-last code-

const title = document.querySelector("div.hello:first-child h1");

console.dir(title);

function handleTitleClick()
{
    title.style.color="blue"; //click -> change color
    console.log("title was clicked!");
}
function handleMouseEnter()
{
    title.innerText="Mouse is here!";
}

function handleMouseLeave()
{
    title.innerText="Mouse is gone!";
}
title.addEventListener("click",handleTitleClick); //괄호를 안넣는다! 왜? js에게 함수 넘겨주고 js가 알아서 실행시킬거기 때문
//js가 title을 지켜보고 있다가 click하는 것을 listen할 것임
//click 하면 handleTitleClick 함수가 작동하길 원함
title.addEventListener("mouseenter",handleMouseEnter);
title.addEventListener("mouseleave",handleMouseLeave);

3.5 More Events

title.addEventListener("click",handleTitleClick); same with down
title.addEventListener("mouseenter",handleMouseEnter);

=둘은 같다!=

title.onclick = handleTitleClick; 
title.onmoueenter=handleMouseEnter;

Window Resize

function handleWindowResize()
{
    document.body.style.backgroundColor="tomato";
}

window.addEventListener("resize",handleWindowResize);


ㄴ 결과값 (사이즈를 다르게 하면 바로 tomato로 색이 바뀐다!)

Copy

function handleWindowCopy()
{
    alert("copier!");
}

window.addEventListener("copy",handleWindowCopy);


ㄴ 결과값 (Ctrl C를 누르면 alert로 나타내준다!)

offline & online

function handleWindowOffline()
{
    alert("SOS no WIFI");
}

function handleWindowOnline()
{
   alert("All Good");
   

window.addEventListener("offline",handleWindowOffline);
window.addEventListener("online",handleWindowOnline);
}


ㄴ 결과값 (WIFI가 꺼지거나 켜지면 경고 메시지 등장)

-last code-

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick()
{
    h1.style.color="blue"; //click -> change color
    console.log("title was clicked!");
}
function handleMouseEnter()
{
    h1.innerText="Mouse is here!";
}

function handleMouseLeave()
{
    h1.innerText="Mouse is gone!";
}

function handleWindowResize()
{
    document.body.style.backgroundColor="tomato";
}

function handleWindowCopy()
{
    alert("copier!");
}

function handleWindowOffline()
{
    alert("SOS no WIFI");
}

function handleWindowOnline()
{
   alert("All Good");
}
h1.addEventListener("click",handleTitleClick);
h1.addEventListener("mouseenter",handleMouseEnter);
h1.addEventListener("mouseleave",handleMouseLeave);

window.addEventListener("resize",handleWindowResize);
window.addEventListener("copy",handleWindowCopy);
window.addEventListener("offline",handleWindowOffline);
window.addEventListener("online",handleWindowOnline);

3.6 CSS in Javascript

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick()
{
    if(h1.style.color==="blue") 
    {
        h1.style.color="tomato";
    }
    else
    {
        h1.style.color = "blue";
    }
}

h1.addEventListener("click",handleTitleClick);

click 하면 blue 또 하면 tomato x 무한

=둘은 같은 결과 도출=

//1. find the element
const h1 = document.querySelector("div.hello:first-child h1");
//3. react the event
function handleTitleClick()
{
    const currentColor=h1.style.color;
    let newColor;

    if(currentColor==="blue") 
    {
        newColor="tomato";
    }
    else
    {
        newColor = "blue";
    }
    h1.style.color=newColor;
}
//2. listen for the event
h1.addEventListener("click",handleTitleClick);

3.7 CSS in Javascript Part two

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick()
{
    if(h1.className==="active")
    {
        h1.className="";
    }
    else{
        h1.className="active";
    }
}

h1.addEventListener("click",handleTitleClick);

이렇게 "active"를 두개 쓰면 error의 위험이 있음

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick()
{
    const clickedClass="clicked";
    if(h1.className===clickedClass)
    {
        h1.className="";
    }
    else{
        h1.className=clickedClass;
    }
}

h1.addEventListener("click",handleTitleClick);

ㄴ 이렇게 써야 함니다 ~~


3.8 CSS in Javascript part Three

class name 바꾸는 다른 방법 -> classList 사용
className = 모든걸 교체해버림, 이전의 class들은 상관 안한다

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick()
{
    const clickedClass="clicked";
    if(h1.classList.contains(clickedClass))
    {
        h1.classList.remove(clickedClass);
    }
    else{
        h1.classList.add(clickedClass);
    }
}
//toggle will check classname exists
h1.addEventListener("click",handleTitleClick);
body{
    background-color: beige;
}

h1{
    color:cornflowerblue;
    transition: color .5s ease-in-out;
}

.active{
    color:tomato;
}

.sexy-font{
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="style.css">
        <title>Momentum App</title>
    </head>
    <body>
        <div class = "hello">
        <h1 class="sexy-font">Click me!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

ㄴ왜 나는 색깔이 안바뀌냐..

toggle

: className이 존재하는지를 체크할 수 있음

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick()
{
    h1.classList.toggle("clicked");
}
//toggle will check classname exists
h1.addEventListener("click",handleTitleClick);

위에 코드랑 같지만 한줄로 해결 가능

0개의 댓글