eajni IT 초보사전 💦💦

[JavaScript] 자바스크립트 기초 (이벤트)

2023-07-29

Events

  • “things” that happen to HTML elements
  • “react” to HTML elements’s action

inline event

  • html 마크업 내부 작성
  • 자바스크립트 파일 작성, 컨텐츠 수정&재사용 용이
  • but 두개 이상 동작 수행 어려움
<button onclick="console.log('hello');">greet</button>
  • ex. inline-onclick
<button id="greetbtn">greet</button>
<script src="app.js></script>
const greetbtn = document.querySelector('#greetbtn');
greetbtn.onclick = function(){
	console.log('hello');
}

Event Handlers

  • every time a page loads
  • whe the page is closed
  • when a user clicks a button
  • when a user inputs data

    addEventListener

  • 주로 사용
<body>
  <h1> what is this color? </h1>
  <button class='btn'>change</button>
</body>
const btn = document.querySelector('.btn');
const h1 = document.querySelector('h1');
btn.addEventListener('click', ()=>{
	const newColor = randomColor();
  	document.body.style.backgroundColor = newColor;
  	h1.innerText = newColor;
})

const randomColor =()=>{
	const r = Math.floor(Math.random() * 255) ;
	const g = Math.floor(Math.random() * 255) ;
	const b = Math.floor(Math.random() * 255) ;
	return `rgb(${r}, ${g}, ${b})` ;
}

mouse event

  • click
  • dbclick

keyboard event

window.addEventListener('keydown', (e)=>{
	console.log('code');
})
  • keydown 키보드를 누를 때 작동
  • keyup
    • code : 입력된 키의 위치 출력 (shiftLeft, keyQ, ArrowLeft …)
    • key : 입력된 내용 출력

input event

  • change 입력 후 포커스가 이동할 때 작동
  • input 입력할 때 즉시 작동
const h1 = document.querySelector('h1');
const username = document.querySelector('#username');

username.addEventListener("input", function(e){
    const updatedName = username.value;
    h1.innerText = `Welcome, ${updatedName}`;
    if(!username.value){
    h1.innerText = "Enter Your Username";
    }
})

form event

  • action에 지정한 위치로 데이터 전송 및 페이지 이동
  • preventDefault() 기본 동작을 작동하지 않음
const form = document.querySelector('form');
const product = document.querySelector('#product');
const qty = document.querySelector('#qty');
const list = document.querySelector('#list');

form.addEventListener('submit', function(e){
    e.preventDefault();
    const pdtext = product.value;
    const qtytext = qty.value;
    const newLI = document.createElement("LI");
    newLI.innerText = `${pdtext} : ${qtytext}`;
    list.appendChild(newLI);
    product.value="";
    qty.value ="";
    
})

event bubbling

  • 중첩 구조마다 이벤트 설정 시, 모든 이벤트 작동
  • stopPropagation() 수행 후 이벤트 중단

event delegation

  • 이벤트 조건 설정 후 새롭게 추가된 요소에 대해서도 이벤트를 작동시키기 위해 상위요소에 이벤트 위임
container.addEventListener('click', fuction(e){
	e.target.nodeName = 'LI' && e.target.remove();

Comments

Content