NomardCoder: greeting-1
greeting 만들기
1.click event : addEventListener( )
<div class="hello">
<h1>Grab me!</h1>
</div>
const title = document.querySelector("div.hello h1");
function handleTitleClick() {
console.log("title was clicked!");
}
title.addEventListener("click", handleTitleClick);
* browser에 나와있는 grab me! 클릭 시
2. click으로 색깔 바꾸기
const title = document.querySelector("div.hello h1")
function handleTitleClick() {
title.style.color = "blue";
}
title.addEventListener("click", handleTitleClick)
* Grab me! 글자 클릭시 색깔이 파란색으로 바뀜
3. 커서를 위에 올려놨을때 event : onmouseenter
- WebAPIs 사이트 접속
https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement
-
js관점에서의 html을 볼수있음. 각종 property/evnet가 있음
-
on이 붙어있는건 event를 줄수 있다는 뜻
const title = document.querySelector("div.hello h1")
function handleMouseEnter() {
console.log('mouse is here!')
}
title.addEventListener("mouseenter", handleMouseEnter);
* 마우스를 grab me! 글자에 올려놓기만 해도 발생
4. 커서가 떠났을때 event : onmouseleave
const title = document.querySelector("div.hello h1")
function handleTitleClick() {
title.style.color = "blue";
}
function handleMouseEnter() {
title.innerText = "mouse is here!"
}
function handleMouseleave() {
title.innerText = 'mouse is leave!'
}
title.addEventListener("click", handleTitleClick)
title.addEventListener("mouseenter", handleMouseEnter);
title.addEventListener("mouseleave", handleMouseleave);
* 마우스를 올려놨을때, 떠났을때 문구가 바뀜
5. window의 event
5-1 event를 줄수있는 방법 2가지
title.addEventListener("click", handleTitleClick)
title.addEventListener("mouseenter", handleMouseEnter);
title.addEventListener("mouseleave", handleMouseleave);
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
title.onclick = handleTitleClick
title.onmouseenter = handleMouseEnter
title.onmouseleave = handleMouseleave
* addEventListener을 선호하는 이유는 나중에 .removeEventListener을 사용 할 수있기 때문!
5-2 resize : 윈도우 창 크기 조절
function handleWindowResize() {
document.body.style.backgroundColor = "tomato";
}
window.addEventListener("resize", handleWindowResize);
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓window창의 크기를 조정했을때↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
5-3 copy: 복사했을때
function handleWindowCopy() {
alert("copier!");
}
window.addEventListener("copy", handleWindowCopy)
* ctrl+c 입력시
응용(if, boolean 등)
const h1 = document.querySelector("div.hello h1")
function handleTitleClick() {
if(h1.style.color === "blue"){
h1.style.color = "tomato"
} else {
h1.style.color = "blue";
}
}
h1.addEventListener("click", handleTitleClick)
* 초기화면
* 클릭했을때 색깔이 블루가 아니기때문에 블루로 바뀜
* 클릭했을때 색깔이 블루이기 때문에 토마토로 바뀜
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓다르게 표현 가능↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
const h1 = document.querySelector("div.hello h1")
function handleTitleClick() {
const currenColor = h1.style.color;
let newColor;
if(currenColor === "blue"){
newColor = "tomato"
} else {
newColor = "blue";
}
h1.style.color = newColor;
}
h1.addEventListener("click", handleTitleClick)
- 글자의 컬러는 currenColor로 할당해주고, newColor는 빈값을 할당함
- 초기 컬러가 블루가 아니기때문에 newColor에 블루를 할당해주고
- 글자 컬러에 newColor를 할당해줌으로써 글자 컬러가 블루가됨
댓글남기기