Java Script

DOM Events

Jassy 2020. 7. 31. 15:59

https://webclub.tistory.com/340

 

event 란 무엇인가?

이벤트(event)란? 이벤트(event)는 어떤 사건을 의미합니다. 브라우저에서의 사건(event)이란 사용자가 클릭을 했을 '때', 스크롤을 했을 '때', 필드의 내용을 바꾸었을 '때'와 같은 것을 의미합니다. ��

webclub.tistory.com

 

1. Events

 

웹의 이벤트 는 기능을 트리거하도록 프로그래밍 할 수있는 사용자 상호 작용 및 브라우저 조작입니다.

 이벤트의 몇 가지 예는 다음과 같습니다.

-버튼을 클릭하는 마우스
-브라우저에서 웹 페이지 파일로드
-이미지에서 바로 스와이프하는 사용자

 


1-1. Events 용어 정리

(출처 : https://opentutorials.org/course/1375/6629)

event target

target은 이벤트가 일어날 객체를 의미한다. 아래 코드에서 타겟은 버튼 태그에 대한 객체가 된다.

1

<input type="button" onclick="alert(window.location)" value="alert(window.href)" />

event type

이벤트의 종류를 의미한다. 위의 예제에서는 click이 이벤트 타입이다. 그 외에도 scroll은 사용자가 스크롤을 움직였다는 이벤트이고, mousemove는 마우스가 움직였을 때 발생하는 이벤트이다.

이벤트의 종류는 이미 약속되어 있다. 아래 링크는 브라우저에서 지원하는 이벤트의 종류를 보여준다.

https://developer.mozilla.org/en-US/docs/Web/Reference/Events

event handler

이벤트가 발생했을 때 동작하는 코드를 의미한다. 위의 예제에서는 alert(window.location)이 여기에 해당한다.

 

 


2. "Firing" Events

 

 DOM) 의 특정 요소에서 특정 이벤트가 발생한 후 응답으로 실행되도록 이벤트 처리기 함수를 만들 수 있습니다. 

이 레슨에서는 이벤트 발생 후 DOM 요소를 수정하고 업데이트하는 이벤트 핸들러 함수에 대해 학습 합니다.

 


3. Event Handler Registration

 

/* 1.  ID로 이벤트 대상으로 사용되는 DOM 요소에 액세스 
 document.getElementById */

let readMore = document.getElementById('read-more')
let moreInfo = document.getElementById('more-info')

/*  이벤트 핸들러 속성을 만듦 
  readMore.onclick  */
readMore.onclick = function () {

/*이벤트 핸들러 함수를 속성에 할당*/
  moreInfo.style.display = 'block';
}

 


4. .addEventListener()

 

.addEventListener()메소드는 이벤트 핸들러를 등록하는 또 다른 일반적인 구문입니다

 

이 방법에는 두 가지 인수가 필요합니다.

- 문자열로 된 이벤트 유형
- 이벤트 핸들러 기능

eventTarget.addEventListener('click', eventHandlerFunction);

 

.addEventListener()메소드를 사용하여 다른 이벤트 핸들러를 변경하지 않고 

여러 이벤트 핸들러를 단일 이벤트에 등록 할 수 있습니다.

 

let view = document.getElementById('view-button');
let close = document.getElementById('close-button');
let codey = document.getElementById('codey');

let open = function() {
  codey.style.display = 'block';
  close.style.display = 'block';
};

let hide = function() {
  codey.style.display = 'none';
  close.style.display = 'none';
};

view.onclick = open;
close.onclick = hide;


let textChange = function() {
  view.innerHTML = 'Hello, World!';
}

let textReturn = function() {
 view.innerHTML = 'View' ;
}

view.addEventListener('click',textChange);
close.addEventListener('click',textReturn);

 

 


 

5. .removeEventListener()

 

이 메소드는 코드가 더 이상 필요하지 않을 때 이벤트가 발생하도록 코드의 "듣기"를 중지합니다. 

.removeEventListener또한 두 가지 인수를 전달합니다.

- 문자열로 된 이벤트 유형
- 이벤트 핸들러 기능

 

.removeEventListener() method must be the same function of the corresponding .addEventListener().

 

let door = document.getElementById('door');
let unlock = document.getElementById('unlock');
let lock = document.getElementById('lock');
let sign = document.getElementById('sign');
let cafeImage = document.getElementById('image');

cafeImage.hidden = true;

let openDoor = function() {
  door.hidden = true;
  cafeImage.hidden = false;
}

let closeDoor = function(){
  door.hidden = false;
  cafeImage.hidden = true;
}

unlock.onclick = function() {
  sign.innerHTML = 'OPEN';
  unlock.style.backgroundColor = '#6400e4';
  lock.style.backgroundColor = 'lightgray';
}

lock.onclick = function() {
  sign.innerHTML = 'CLOSED';
  lock.style.backgroundColor = '#6400e4';
  unlock.style.backgroundColor = 'lightgray';
}

unlock.addEventListener('click', function(){
  door.addEventListener('click', openDoor);
  cafeImage.addEventListener('click', closeDoor);
})

/*
First, you must add an event listener to the lock element
when a click event is fired with an anonymous function.

Inside the function, add a .removeEventListener() to turn off the openDoor function 
when a user tries to click the door element. 
Then run your code and fire the event to test out your event handlers.
*/
lock.addEventListener('click', function() 
{
  door.removeEventListener('click',openDoor)
})

 

 


 

6. Event Object Properties

 

JavaScript는 관련 데이터 및 기능을 속성 및 메서드로 사용하여 이벤트를 이벤트 객체 로 저장합니다 . 

이벤트 객체와 관련된 미리 결정된 속성이 있습니다. 이러한 속성을 호출하여 이벤트에 대한 정보를 볼 수 있습니다

 

예 :
.target : 이벤트를 트리거 한 요소에 액세스하기 위한 속성
.type : 이벤트의 이름에 액세스 하는 프로퍼티
.timeStamp : 문서가 로드되고 이벤트가 트리거 된 후 경과 된 시간 (밀리 초)에 액세스 하는 특성입니다.

 

let social = document.getElementById('social-media');
let share = document.getElementById('share-button');
let text = document.getElementById('text');


let sharePhoto = function(event) {
  event.target.style.display = 'none';
  text.timeStamp.innerHTML;
}

share.onclick = sharePhoto;

 

 


 

7. Event Types

 

click이벤트 외에도 브라우저에서 실행할 수있는 모든 유형의 DOM 이벤트가 있습니다! 

연결된 이벤트 핸들러가 없기 때문에 DOM에서 대부분의 이벤트가 눈에 띄지 않고 발생 한다는 것을 알아야 합니다.

또한 등록 된 일부 이벤트는 사용자 상호 작용에 의존하지 않는 것이 중요합니다. 

예를 들어, load웹 사이트 파일이 브라우저에 완전히로드 된 후에 이벤트가 발생합니다.

브라우저는 사용자없이 많은 다른 이벤트를 발생시킬 수 있습니다 . 

MDN 이벤트 참조 페이지 에서 이벤트 목록을 확인할 수 있습니다 .

 

// This variable stores the "Pick a Color" button
let button = document.getElementById('color-button');

// This variable stores the "Mystery Color" button
let mysteryButton = document.getElementById('next-button');

// This random number function that will creates color codes for the randomColor variable
function rgb(num) {
  return Math.floor(Math.random() * num);
}

// Write your code below
let colorChange = function (event) {
  let randomColor = 'rgb(' + rgb(255) + ',' + rgb(255) + ',' + rgb(255) + ')';
  event.target.style.backgroundColor = randomColor;
}

button.onclick = colorChange;
mysteryButton.onwheel = colorChange;

 

 


 

8. Mouse Events

 

-

 

8-1.mousedown

 

mousedown사용자가 마우스 버튼을 아래로 누르면 이벤트가 발생합니다.

마우스 버튼을 놓아 발사 할 필요가 없기 때문에 click이벤트 와 다릅니다

 

*

 

8-2. mouseup

mouseup사용자가 마우스 버튼을 놓을 때 이벤트가 발생합니다. 

마우스 버튼을 눌렀다가 발사하는 것에 의존하지 않기 때문에 이것은 click및 mousedown이벤트 와 mouseup다릅니다.

 

*

 

8-3. mouseover

mouseover마우스가 해당 범위 안에 들어오면 이벤트가 발생합니다.

*

 

8-4. mouseout

mouseout마우스가 요소를 벗어날 때 이벤트가 발생합니다.

// These variables store the boxes on the side
let itemOne = document.getElementById('list-item-one');
let itemTwo = document.getElementById('list-item-two');
let itemThree = document.getElementById('list-item-three');
let itemFour = document.getElementById('list-item-four');
let itemFive = document.getElementById('list-item-five');
let resetButton = document.getElementById('reset-button');

// This function programs the "Reset" button to return the boxes to their default styles
let reset = function() {
  itemOne.style.width = ''
  itemTwo .style.backgroundColor = ''
  itemThree.innerHTML = 'The mouse must leave the box to change the text'
  itemFive.style.display = "none"
};
resetButton.onclick = reset;


itemOne.onmouseover = function () {
  itemOne.style.width = '300px';
}

itemTwo.onmouseup = function () {
  itemTwo.style.backgroundColor = 'blue';
}

itemThree.onmouseout = function () {
  itemThree.innerHTML = 'The mouse has left the element.';
}


itemFour.onmousedown= function () {
  itemFive.style.display = 'block';
}

 

 


 

9. Keyboard Events

 

-

 

9-1. keydown 

 

용자가 키 아래를 누를 때 이벤트가 발생합니다.

 

*

 

9-2. keyup 

 

사용자가 키를 놓을 때 이벤트가 발생합니다.

*

 

9-3. keypress 

 

사용자가 키 아래 해제를 누를 때 이벤트가 발생합니다. 

이벤트 keydown와 keyup이벤트를 함께 사용하는 것과는 다릅니다. 

이벤트는 두 개의 완전한 이벤트이며 keypress하나의 완전한 이벤트 이기 때문 입니다.

 

let ball = document.getElementById('float-circle');

let up = function ( ) {
  ball.style.bottom = '250px';
}

let down  = function ( ) {
  ball.style.bottom = '50px';
}

document.onkeydown = up;
document.onkeyup= down;