word-relay 예제 따라하기 - 이벤트 편

Nian·2022년 5월 2일
0

참조

  1. 이 글은 "Let's Get IT 자바스크립트 프로그래밍"의 예제를 따라면서 자습하는 글입니다.
  2. 별도로 인터넷에서 찾아 작성한 예제도 포함될 수 있습니다. (출처 명시)

1. 확인할 코드

<script>
	const onClickButton = () => {
    	console.log('버튼 클릭');
    };
    const $button = document.querySelector('button')
    $button.addEventListener('click', onClickButton)
</script>

2. 공부한 부분

addEventListener()

  • 참조 : https://ordinary-code.tistory.com/64

  • 지정한 유형의 이벤트를 대상이 수신할 때마다 호출할 함수 설정하는 매서드.

  • 구문

    	addEventListener(이벤트명, 실행할 함수명, 옵션)

이벤트명 : Javascript에서 발생할 수 있는 이벤트명
함수명 : 해당 이벤트가 발생할 때 실행할 함수명. 생략가능.
옵션 : 이벤트 수신기의 특징을 지정할 수 있는 객체.
*옵션에 대한 내용은 이 사이트(https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault)를 참조

<!doctype html>
<head>
<body>
	<table id="outside">
    	<tr><td id="t1">one</td></tr>
        <tr><td id="t2">two</td></tr>
    </table>
<script>
	// t2의 콘텐츠를 바꾸는 함수
	function modifyText() {
    	const t2 = document.getElementById("t2");
        if (t2.firstChild.nodeValue == "three") {
        	t2.firstChild.nodeValue = "two";
        } else {
        	t2.firstChild.nodeValue = "three";
        }
    }
    // 표에 이벤트 수신기 추가
    const el = document.getElementById("outside");
    el.addEventListener("click", mdoifyText, false);
</script>
</body>
</html>

참고사항 : removeEventListener()

해당 이벤트 리스너를 제거하는 기능

const body = document.querySelector('body')
const clickTarget = document.getElementById('click-target')
const mouseOverTarget = document.getElementById('mouse-over0target')

let toggle = false;
function makeBackgroundYellow() {
	if (toggle) {
    	body.style.backgroundcolor = 'white';
    } else {
    	body.style.backgroundColor = 'yellow';
    }
    
    toggle = !toggle;
}

clickTarget.addEventListener('click', makeBackgroundYellow, false);

mouseOverTarget.addEventListener('mouseover', function() {
	clickTarget.removeEventListener('click', makeBackgroundYellow, false);
});
profile
무언가를 하고 있지만, 잘 안될 수 있습니다.

0개의 댓글

관련 채용 정보