40.8.1 DOM 요소의 기본 동작 중단

preventDefault 메서드 이용

<!DOCTYPE html>
<html>
<body>
	<a href="<http://www.google.com>">go</a>
	<input type="checkbox">
	<script>
		document.querySelector('a').onclick = e => {
			// a 요소의 기본 동작(지정된 링크로 이동)을 중단
			e.preventDefault();
		}
		document.querySelector('input[type=checkbox]').onclick = e => {
			// checkbox 요소의 기본 동작(체크 또는 해제)을 중단
			e.preventDefault();
		}
	</script>
</body>
</html>
<body>
  <form>
    <input type="checkbox" placeholder="값을 입력하세요">
  </form> 

  <script>
    document.querySelector('input[type=checkbox]').onclick = e => {
      e.preventDefault();
      console.log("실패");
    }
  </script>
</body>

Untitled

⇒ 체크박스 선택 불가

40.8.2 이벤트 전파 방지

stopPropagation 메서드

<!DOCTYPE html>
<html>
<body>
	<div class="container">
		<button class="btn1">Button 1</button>
		<button class="btn2">Button 2</button>
		<button class="btn3">Button 3</button>
	</div>
	<script>
		document.querySelector('.container').onclick = ({ target }) => {
			if(!target.matches('.container > button')) return;
			target.style.color = 'red';
		}
		document.querySelector('.btn2').onclick = e => {
			e.stopPropagation();
			e.target.style.color = 'blue';
		}
	</script>
</body>
</html>

Untitled

40.9.1 이벤트 핸들러 어트리뷰트 방식

<!DOCTYPE html>
<html>
<body>
	<button onclick="handleClick()">Click me</button>
	<script>
		function handleClick(button){
			console.log(button); // 이벤트를 바인딩한 button 요소
			console.log(this); // window
		}
	</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
	<button class="btn1">0</button>
	<button class="btn2">0</button>
	<script>
		const $button1 = document.querySelector('.btn1');
		const $button2 = document.querySelector('.btn2');

	//이벤트 핸들러 프로퍼티 방식
	$button1.onclick = function(e) {
		//this는 이벤트를 바인딩한 DOM 요소를 가리킨다.
		console.log(this); // $button1
		console.log(e.currentTarget); // $button1
		console.log(this === e.currentTarget); // true

		// $button1의 textContent를 1 증가시킨다.
		++this.textContent;
	}

	//addEventListener 메서드 방식
	$button2.addEventListener('click', function(e) {
		//this는 이벤트를 바인딩한 DOM 요소를 가리킨다.
		console.log(this); // $button2
		console.log(e.currentTarget); // $button2
		console.log(this === e.currentTarget); // true

		// $button2의 textContent를 1 증가시킨다.
		++this.textContent;
	});
	</script>
</body>
</html>