JaveScript
[노마드코더] Vanilla_Js (3강 - Javascript와 HTML 상호작용,Event)
SanL
2023. 5. 10. 02:27
Javascript와 HTML 상호작용
:JavaScript에서 HTML을 불러올 수도 있고, JavaScript에서 수정도 할 수 있음
document.title = "change tilte"; // title이 change tilte로 바뀜
const any = document.getElementById("id이름"); // html에서 해당 id값을 가진 태그를 가져옴
any.innerText = "Hello~~"; // 태그 안에 text가 바뀜 즉, Js안에서, html을 수정함.
const classNames = document.getElementsByClassName("class이름"); // html에서 해당 class를 가진 태그를 모두 가져옴(배열의 형태)
// 여기서 id와 class의 차이가 나옴. id는 보통 특정 하나의 태그에 부여할 때 사용하고 class는 다수의 태그에 사용
const tagNames = document.getElementsByTagName("tag이름"); // html에서 해당 태그를 모두 가져옴(배열의 형태)
const querySelector = document.querySelector("class이름/id이름/tag이름 class이름/id이름/tag이름");
// 이러면 특정 태그 하위에 있는 태그만 가져올 수 있음
// 여러개 있으면 가장 위에있는 것만 가져옴
// 모두 가져오고 싶다면 querySelectorAll 사용(배열의 형태)
//getElementById("hello")와 querySelector("#hello")는 같음
- 만약 element요소 추가적으로 확인하고 싶은 경우 console.dir(참고하고싶은 태그)
ex)innerText, title, namem id....
Event - 간단한 event의 로직
const title = document.querySelector("div.hello:frist-child h1");
function handleTitleClick(event) {
console.log("title was clicked")
}
function handleMouseEnter(event) {
console.log("mouse is here")
}
title.addEventListener("click", handleTitleClick);
title.onclick = handleTitleClick; // title.addEventListener("click", handleTitleClick)과 동일한 기능
title.addEventListener("mouseenter", handleMouseEnter);
title.onmouseenter = handleMouseEnter; // title.addEventListener("mouseenter", handleMouseEnter)과 동일한 기능
//event중에 moseenter이라는이벤트를 선택 후 그 이벤트가 발생했을때 console.log
//click event를 listen하고, 이 click event가 발생하면
// handleTitleClick이라는 fuction이 동작하길 바람
//즉,유저가 title을 click할 경우에 javascript가 실행버튼을 대신 눌러주길 바람
//click event를 listen하기 위해서는, HTML element를 가져와서, addEventListener을 실행시켜주면됨
//이떄 이곳에 어떤 event를 listen하고 싶은지를 명시해줘야함
//click 이벤트를 사용하고 싶은지, 마우스가 element위에 올라갔을 때 이벤트를 실행시키고 싶은지를 알려줘야함
다양한 Event 사용
[main HTML]
<!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>Momentum App</title>
<link rel = "stylesheet" href = "style.css">
</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>
[app.js-file]
const title = document.querySelector(".hello:first-child h1");
// html에서 hello태그를 가져옴
function handleTitleClick() {
const currentColor = title.style.color;
let newColor;
if (currentColor === "blue"){
newColor = "tomato";
}else {
newColor = "blue";
}
title.style.color = newColor;
}
// 조건문 if-else를 사용하여 클릭할 때마다 색을 바꿔줌
title.addEventListener("click", handleTitleClick); // ('이벤트종류', 실행할 함수)
// title을 클릭할 시 이벤트가 발생하고 handleTitleClick() 함수를 실행
function handleWindowResize() {
document.body.style.background = "tomato";
}
window.addEventListener("resize", handleWindowResize)
// 전체 창의 크기가 바뀌면 함수 호출
function handleWindowOffline() {
alert("SOS no WIFI");
}
window.addEventListener("offline", handleWindowOffline);
// 인터넷 연결이 끊겼을 때 함수 호출
function handleWindowOnline() {
alert("Good WIFI");
}
window.addEventListener("online", handleWindowOnline);
// 인터넷 연결이 되었을 때 함수 호출
//contain = 해당 클래스가 HTML element에 포함되어 있나
// grab.classList.toggle("clicked") = grab의 classList에 clicked가 있는지 확인해서 있으면 제거 없으면 추가
event에 관한 추가적인 기능들을 좀 더 자세히 살펴보는 경우 <MDN Web Docs 웹사이트 > 참고