event란?
웹 브라우저와 사용자 사이에 상호작용이 발생하는 특정시점을 의미함.
이벤트가 발생하면, 이벤트 종류에 따라 어떤 작업을 하거나 미리 등록한 함수를 호출하는 등의 조작을 지정가능
이벤트 종류
이벤트 등록하기
: 어떤 작업을 할지 자바스크립트 코드로 작성하는 것으로 방법은 아래와 같이 3가지가 있다.
1) 인라인 방식으로 이벤트 등록
2) 프로퍼티 리스너
3) 이벤트 등록 메소드
1. 인라인 방식으로 이벤트 등록
: HTML 태그에 속성으로 이벤트 등록하는 방법
: 속성값으로 이벤트가 발생할 때 실행될 함수를 지정해주면 예를 들어 버튼을 클릭할 때(onclick) 해당 함수가 실행.
<body>
<button onclick="mouseClick()">클릭</button>
<script>
function mouseClick(){
alert("click");
}
</script>
</body>
<body>
<button onclick="mouseClick()">클릭</button>
<input onmouseover="FocusEvent()" type="text" name="txt" id="txt">
<script>
function mouseClick(){
alert("click");
}
function FocusEvent(){
console.log("Focus in");
}
</script>
실제로 이벤트를 달리하니까 onmouseover처럼, 올리니까 console창에 출력되고 변화가 있었다.
책에 있는 FocusEvent가 내장되어 있는거 같은데 이 부분에 대해서 나중에 좀 더 봐야겠다
2. 프로퍼티 리스너(property listener) 방식으로 이벤트 등록하기
: 요소 노드에 직접 속성으로 이벤트 등록
<body>
<button>클릭</button>
<input onmouseover="FocusEvent()" type="text" name="txt" id="txt">
<script>
const btn = document.querySelector("button");
btn.onclick = function(){
console.log("mouseMove");
}
function mouseClick(){
alert("click");
}
function FocusEvent(){
console.log("Focus in");
}
</script>
</body>
btn.onclick 부분이 바로 property listener 방식이다.
화살표 함수로도 가능하다.
btn.onclick = () => {
alert("arrow click");
}
또한, 함수를 별도로 정의하고 함수명을 이용해 이벤트와 연결할 수도 있다.
btnEl.onclick = clickEvent;
function clickEvent(){
alert("click");
}
3. 이벤트 등록 메서드로 이벤트 등록하기
addEventListener()을 사용해서 이벤트를 등록할 수 있다. 가장 권장하는 방식
<노드>.addEventListener("<이벤트타입>", <이벤트 함수>);
이벤트 타입은 아래 표에서 on만 빼면 된다. 그것이 타입.
예시를 통해 이해해보자면
<button>클릭</button>
<script>
const btn = document.querySelector("button");
btn.addEventListener("click", function(){
alert("button Click");
});
</script>
<button>클릭</button>
<script>
const btn = document.querySelector("button");
btn.addEventListener("click", afterClick);
function afterClick(){
alert("button Click");
}
</script>
<button>클릭</button>
<script>
const btn = document.querySelector("button");
const afterClick = () => {
alert("button Click");
};
btn.addEventListener("click", afterClick);
</script>
이벤트 객체와 this
이벤트 객체는 이벤트가 발생하면 실행되는 함수의 매개변수로 같이 전달된다.
이벤트 객체 사용하기
이벤트가 발생하면, 실행되는 함수에는 내부적으로 이벤트 객체가 매개변수로 전달된다.
이벤트 함수에는 이벤트 객체라는 데이터가 내부적으로 전달되어 호출된다!
<button>클릭</button>
<script>
const btnEl = document.querySelector("button");
btnEl.addEventListener("click",function(event){ // 이벤트 객체
console.log(event);
</script>
아래로 확인할 수 있다.
console.log(`clientX:${event.clientX}`);
console.log(`clientY :${event.clientY }`);
console.log(`pageX:${event.pageX}`);
console.log(`pageY:${event.pageY}`);
console.log(`screenX:${event.screenX}`);
console.log(`screenY :${event.screenY }`);
이 이벤트 객체 event의 속성도 활용할 수 있다.
아래는 PointerEvent 객체이다.
KeyboardEvent 객체도 사용된다. 아래는 키보드 속성이다.
이벤트 취소하기
: a와 form 태그처럼 기본이벤트가 있는 것을 취소할 수 있는 방법
preventDefault() 메서드를 사용하면, 태그에 기본으로 연결된 이벤트를 취소할 수 있다.
이것도 addEventListener()로 추가한다.
예시를 보자
<a href="https://www.naver.com">네이버 이동</a>
<a href="https://www.daum.net">다음 이동</a>
<script>
const aEls = document.querySelectorAll("a");
for(let i = 0; i < aEls.length; i++){
aEls[i].addEventListener("click", function(e){
e.preventDefault(); // 기본 이벤트 취소
});
}
</script>
querySelectorAll로 노드리스트를 가져와 각각 인덱스로 접근해 preventDefault()를 추가해준다.
this 키워드 사용하기
: this를 사용하면, 이벤트가 발생한 요소 노드를 바로 가리킬 수 있다.
<p>text-1</p>
<p>text-2</p>
<p>text-3</p>
<script>
const pEls = document.querySelectorAll("p");
pEls.forEach((el) => {
el.addEventListener("click", function(){
console.log(this);
});
})
</script>
출력결과, 이벤트가 발생한 대상 노드를 가리킴을 알 수 있다.
this를 활용해서 p태그를 클릭하면 텍스트 색상을 빨간색으로 바꾸고, 이미 빨간색이면 검은색으로 바꾸는 코드
<script>
const pEls = document.querySelectorAll("p");
pEls.forEach((el) => {
el.addEventListener("click", function(){
if(this.style.color === 'red'){
this.style.color = 'black';
}else{
this.style.color = 'red';
}
});
})
</script>
하지만 this를 쓸땐 화살표 함수 안 쓰는 것이 좋음. this의 범위가 달라질 수 있기 때문.
'Frontend > JavaScript' 카테고리의 다른 글
[JavaScript] 폼 조작하기 (0) | 2023.07.31 |
---|---|
[JavaScript] document-2 (노드 조작/추가,삭제) (1) | 2023.07.30 |
[JavaScript] 문서 객체 모델 이해하기 (document편-1) (0) | 2023.07.29 |
[JavaScript] 브라우저 객체 모델 사용하기 (Window편) (1) | 2023.07.29 |
[JavaScript] 표준 내장 객체 사용하기 (1) | 2023.07.29 |