본문 바로가기
시작/TIL(Today I Learned)

221108 JavaScript - 이벤트 (EVENT)

by 백씨네 2022. 11. 9.
728x90

오늘 내가 배운 것

1. 이벤트 (Event)

2. 이벤트 적용하기

  • 이벤트 적용하기 1
  • 이벤트 적용하기 2
  • 이벤트 적용하기 3

3. 이벤트 객체

 

 

 

1. 이벤트

 

브라우저 기준으로 설명하면 렌더 된 영역에서 `click`, `mouseover`, `mouseout` 등 특정한 행동을 했을 때 특정한 함수를 호출하는 것,

브라우저에서 이미 구현해놓은 규칙에 맞게 우리가 맞춰 사용하면 된다.(DOM)

 

 

2-1. 이벤트 적용하기 1

이벤트 적용하기 1 - HTML과 JS를 이용한다.

html이랑 js를 같이 써서 구현하는 방법 

속성명에 on이 붙으면 대부분 EVENT이다. 
on + 이벤트명 : onClick  /  onMouseover / onMouseout

 

<!-- element 속성에다가 어떠한 이벤트명을 입력해서 사용하는 방법 -->
<button onClick="alert ('hello, world!')">버튼</button>  
<!-- html의 body에 작성한다. -->

div에 style속성을 작성할 때 CSS문법에 맞춰서 작성했었다.
그것처럼 onClick도 JavaScript 문법에 맞춰서 적어 주면 된다.

`Q. button태그는 실행이 언제 되느냐?` - onClick
엘리먼트 버튼을 클릭하였을 때 코드가 실행이 된다. 함수가 호출 시 바로 실행되는 것이 아니다..

 

2-2. 이벤트 적용하기 2

이벤트 적용하기 2 - DOM 속성으로 넣는 방법


1. JS로 해당 element를 선택할 줄 알아야한다.
2. 선택한 element의 onClick 속성에 함수 선언 후 대입한다.

스크립트를 body에 넣어야 html element를 찾을 수 있다!

 

const btn = document.querySelector (".btn") 
console.log(btn)// button.btn 출력되고 밑에 속성 값을 확인할 수 있다. - 참조형

//btn의 onclick 속성에 함수(원하는 동작)를 직접 대입한다.
btn.onclick = function(){
    console.log("Hello, world!2")
}

button.btn 의 속성 값 중 on- 은 다 이벤트이다.
그중 onclick의 값이 `null` 이다. (=== 할당된 것이 없으므로 클릭을 하더라도 아무 동작을 하지 않는다.)

 

방법 1과 방법 2의 단점

(->addEventListener 가 생긴 이유)

함수를 2개 이상 쓰고 싶은 경우가 생긴다. 속성에다가 함숫값을 넣어 버리면 함수를 하나밖에 못 넣지 않느냐?
-해당 Element에다가 복수 이벤트를 넣을 수 있게 해 준다. (2개 이상)

더보기
const btn = document.querySelector (".btn") 
console.log(btn)

btn.onclick = function(){
    console.log("hello")
}
btn.onclick = function(){
    console.log("hello2")
}
//btn의 함수는 1개 밖에 없는데 그 함수의 속성값에 위에서 대입해주고 밑에서 재할당을 시켜준 모양 ( 값이 바뀌었다.)


const person = {
    name : "gildong",
    run : function(){
        console.log(this.name + "달린다!")
    },
}

person.run()

person.run = function (){
    console.log(this.name + "걷는다")
} // run을 재할당 하는 것과 같은 의미

person.run() = function(){
    console.log(this.name + "달린다!")
}

person.run() //을 하면 두번 재할당해서 초기 값이 됨  // 이게 문제다..
const person = {
    name : "gildong",
    run : function(){
        console.log(this.name + "달린다!")
    },
}

person.run()
function personRun(){
    console.log(this.name + "걷는다.")
}

person.run = personRun  // 이렇게 넣어야함.
person.run = personRun() // 함수가 호출이 되고 함수의 리턴 값이 대입되기 때문에 person객체의 run은 undefined가 되고,
person.run() // Type Error : not a function

// 중요한 부분!! 함수를 호출할 때 ()가 있냐 없냐는 값이 너무 달라지니 꼭 확인할 것..!

함수로 선언하고 넣으면 이벤트를 삭제하기 용이하다.

 

 

2-3. 이벤트 적용하기 3

이벤트 적용하기 3 

1. 이벤트 등록하기 - addEventListener()

//기본 문법
// event
//on click   mouseover   mouseout


element.addEventListener('event':string, 함수값)
//함수 두개가 출력 되는가?
const btn = document.querySelector(".btn")

btn.addEventListener('click', function (){
    console.log("world!!!")
})
btn.addEventListener('click', function (){
    console.log("world2!")
})

//함수로 문법을 표현해보면...
function listener(event, callback){
    if(event === 'click'){
        callback()
    }
}

function handler(){
    console.log("helloooo1")
}

listener('click' , handler)

// listener('click' , function(){
//     console.log("hellooo!")
// })


//addEventListener 은 기본적으로 함수 그대로 파라미터에 넣지만, 변수로 지정해서 함수를 선언해서 넣기도 한다.
const btnHandler = function (){
    console.log('hello world~~~')
}
btn.addEventListener('click', btnHandler){

}

 

 

 

2. 이벤트 삭제하기 - removeEventListener()

//기본 문법
Element.removeEventListener (이벤트 : string, 함수값 : function)

 

btn.removeEventListener('click', function() ){
    console.log("hello_world!")
}

removeEventListener 사용하여 handler 지우기

// handler만 지우고 싶다
const btn = document.querySelector(".btn")

function handler (){
    console.log("hello, world!@#!@#")
}
function handler2 (){
    console.log('hello, world!@#$@')
}

btn.addEventListener("click" , handler)
btn.addEventListener("click" , handler2)

btn.removeEventListener ("click", handler)

//가장 이상적인 코딩스타일
//장점 : 코드블럭의 댑스가 높지 않다.. (탭이 적다. == 가독성이 좋다.)

 

Q. 만약 버튼 2도 똑같은 이벤트를 등록하고 싶다

<button class="btn">버튼</button>
<button class="btn2">버튼2</button>
//위에 코드 연장 시점.
const btn = document.querySelector(".btn")

function handler (){
    console.log("hello, world!@#!@#")
}
function handler2 (){
    console.log('hello, world!@#$@')
}
//위에 코드 연장 종점



// 만약 버튼2도 똑같은 이벤트를 등록하고 싶다
const  btn2 = document.querySelector(".btn2")
btn2.addEventListener("mouseover", handler2)

//코드 재활용가능!

 

4. 이벤트 객체

 

e.target : 이벤트를 발동시킨 타겟 (타입 : 엘리먼트) //  내가 실행시킨 요소가 어떤 것인지 알려준다.
handler가 "btn" or "btn2"중에 누구에 의해 실행되었는지 알려줌

e.type : addEventListenter 썼던 첫 번째 parameter을 그대로 출력한다.(무슨 이벤트로 인해 코드가 실행됐는가)

 

const btn = document.querySelector(".btn")
const btn2 = document.querySelector(".btn2")
const display = document.querySelector("#display")

function handler(e) {
    console.log(e.target)
    console.log(e.type)
    console.log("hello world!")
    // display.innerHTML = "이벤트발동!"
    if(e.typev === 'click'){
        display.innerHTML = "마우스를 클릭했다."
    }else if (e.type=== 'mouseover'){
        display.innerHTML = "마우스를 올렸다"
    }

}
btn.addEventListener('click', handler)
btn2.addEventListener('mouseover', handler)
//e : 이벤트 객체(event object) : 데이터 타입은 object
function handler2 (e) {
        //e. target : object 이지만 element 내용만 가지고 있음
        console.log(e.target)
        
        e.target.style = "dispaly : none;" // css문법
        //handler2 가 실행될 때 display의 속성을 none으로 바꾸겠다.
}
display.addEventListeter('click', handler2)

console.dir(display) : display 안에 있는 객체를 다 보여준다.

 

display.className = 'b' // class를 'b'로 바꾸겠다.
display.className = 'b box' // class를 'b'와 'box' 2개를 쓴다
// const text = "b box"
// const classList = text. split(" ") // ['b', 'box'] 배열로 표현해준다.
// classList[0] = 'a'

 console.log(display.classList)  
 // display.classList[0] = 'a'   //작동이 안된다
 // classList 라서 ! 
 // 이렇게 바꾸는 것이 아니라 특정한 메서드를 이용해서 바꿔주어야함

 //.push() 처럼 뒤에 하나 추가 된다.
 display.classList.add("view")
 //box 클래스 지우기
 display.classList.remove("box")
 display.classList.remove('b')

classNameclassList 구분을 잘해야 한다.

반응형

댓글