JS

JS 이벤트 처리 - 기본

ryeonng 2024. 7. 24. 10:48

 

HTML 요소에 이벤트 등록하기

자바스크립트 이벤트는 웹 페이지에서 발생하는 다양한 동작이나 발생 상황을 나타낸다. 이런 이벤트를 활용하여 사용자의 행동에 반응하는 동적인 웹 페이지를 만들 수 있다. 예를 들어, 사용자가 버튼을 클릭할 때 메시지가 나타나게 하거나, 마우스를 웹 페이지의 특정 부분에 올렸을 때 스타일이 변경되게 할 수 있다.

 

이벤트를 활용하려면, 먼저 HTML 요소에 이벤트를 등록해야 한다.

 

이벤트 등록의 대표적인 3가지 방식

  • Inline Event Handler : HTML 요소 내부에 직접 이벤트를 등록한다.
  • Element Property : 자바스크립트에서 HTML 요소의 프로퍼티로 이벤트를 등록한다.
  • addEventListener() 메서드 : 가장 권장되는 방식으로, 여러 이벤트 리스너를 동일한 요소에 추가할 수 있다.
  • 단, 비동기 통신으로 페이징 할 경우 Inline Event Handler 권장

 

Inline Event Handler

HTML 요소 내부에 직접 이벤트를 등록하는 방식

<button onclick="alert('Inline Event Handler!')">Click me!</button>
이벤트 핸들러
이벤트 핸들러는 특정 이벤트가 발생했을 때 실행되는 함수 또는 메서드를 말한다. 즉, 이벤트 핸들러는 특정 이벤트가 일어났을 때 어떤 동작이 실행될지를 정의하고, 이벤트가 발생하면 그에 따라 코드를 실행한다.

 

 

Element Property

자바스크립트에서 HTML 요소의 프로퍼티로 이벤트를 등록하는 방식

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Element Property Example</title>
	</head>
	<body>
		<button id="myButton">Click me!</button>
		<script>
			// 버튼 요소에 접근
			let btn = document.getElementById("myButton");

			// onclick 프로퍼티로 이벤트 핸들러 등록
			btn.onclick = function () {
				alert("HTML 요소의 속성으로 이벤트를 등록 하고 실행 합니다.");
			};
		</script>
	</body>
</html>

 

 

addEventListner() 메서드

addEventListener() 메서드를 사용하여 이벤트 핸들러를 등록하는 방식

이 방식은 여러 이벤트 리스너를 동일한 요소에 추가할 수 있다.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>addEventListener() Example</title>
	</head>
	<body>
		<button id="myButton">Click me!</button>
		<script>
			// 버튼 요소에 접근
			let btn = document.getElementById("myButton");

			// addEventListener() 메서드로 이벤트 핸들러 등록
			btn.addEventListener("click", function () {
				alert("addEventListener() Event Handler!");
			});
		</script>
	</body>
</html>

이 방법은 HTML과 JavaScript 코드를 분리하여 유지 보수를 쉽게 할 수 있다. addEventListner() 메서드는 이벤트 이름과 이벤트 핸들러 함수를 인자로 받는다.

 

1. click : 요소를 클릭할 때 발생합니다.
2. dblclick : 요소를 더블 클릭할 때 발생합니다.
3. mousedown : 요소에서 마우스 버튼이 눌릴 때 발생합니다.
4. mouseup : 요소에서 마우스 버튼이 떼어질 때 발생합니다.
5. mousemove : 요소에서 마우스가 움직일 때 발생합니다.
6. mouseover : 요소에 마우스 커서가 올라갈 때 발생합니다.
7. mouseout : 요소에서 마우스 커서가 벗어날 때 발생합니다.
8. keydown : 키보드에서 키를 누를 때 발생합니다.
9. keyup : 키보드에서 키를 뗄 때 발생합니다.
10. submit : 폼을 제출할 때 발생합니다.
11. change : 요소의 값이 변경될 때 발생합니다.
12. load : 웹 페이지나 이미지 등이 로딩되었을 때 발생합니다.

 

 

이벤트 등록 및 이벤트 핸들러 처리

시나리오 코드 - 숨기기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .flex--container {
            display: flex;
        }

        .box {
            border: 1px solid black;
            padding: 10px;
        }
    </style>
</head>
<body>
    <h1>숨기기</h1>
    <!-- div.flex--container>button*2 -->
    <div class="flex--container">
        <!-- Inline Event Handler 방식 사용 -->
        <button onclick="hideDisplay()">display로 숨기기</button>
        <button onclick="hideVisible()">visible로 숨기기</button>
    
        <div class="box">
            <!-- div.box#innerBox1 -->
            <div class="box" id="innerBox1">내부박스1</div>
            <div class="box" id="innerBox2">내부박스2</div>
        </div>
    </div>

    <script>
        function hideDisplay() {
            let el = window.document.querySelector("#innerBox1"); // innderBox1 요소가 통으로 담김
            el.style.display = 'none'; 
        }

        function hideVisible() {
            let el = document.querySelector("#innerBox2");
            el.style.visibility = "hidden";
    
     // display 속성과 visibility 속성의 차이를 알아보자
        }
    </script>

    

</body>
</html>

display: none 과 visiblity: hidden 은 모두 HTML 요소를 숨기는 방법이지만, 그들 사이에는 몇 가지 중요한 차이점이 있다.

 

1. 공간 차지

display: none

  • 요소를 완전히 숨기며, 요소가 차지하던 공간도 제거된다.
  • 즉, 화면에서 요소가 완전히 사라지고 그 자리를 다른 요소들이 차지할 수 있게 된다.

visiblity: hidden

  • 요소는 화면에서 보이지 않지만, 요소가 차지하던 공간은 유지된다.
  • 즉, 요소가 보이지 않게 되지만, 그 자리는 계속 차지하고 있어서 페이지 레이아웃에 영향을 주지 않는다.

 

2. 이벤트 발생

display: none

  • 요소가 완전히 비활성화되어, 이벤트를 발생시킬 수 없다.

visiblity: hidden

  • 이벤트는 발생하지 않지만, 만약 자식 요소가 visibility: visible로 설정되어 있다면, 자식 요소에서는 이벤트가 발생할 수 있다.

 

시나리오 코드 - 보이기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .flex--container {
            display: flex;
        }

        .box {
            border: 1px solid black;
            padding: 10px;
        }

        #innerBox1 {
            display: none;
        }

        #innerBox2 {
            visibility: hidden;
        }
    </style>
</head>
<body>
    <h1>보이기</h1>
    <!-- div.flex--container>button*2 -->
    <div class="flex--container">
        <!-- Inline Event Handler 방식 사용 -->
        <button onclick="showDisplay()">display로 보이기</button>
        <button onclick="showVisible()">visible로 보이기</button>
    
        <div class="box">
            <!-- div.box#innerBox1 -->
            <div class="box" id="innerBox1">내부박스1</div>
            <div class="box" id="innerBox2">내부박스2</div>
        </div>
    </div>

    <script>
        function showDisplay() {
            let el = window.document.querySelector("#innerBox1");
            el.style.display = 'block'; 
        }

        function showVisible() {
            let el = document.querySelector("#innerBox2");
            el.style.visibility = "visible";
    
     
        }
    </script>

    

</body>
</html>

 

실습 예제 - 노드 생성하기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<style>
    ul {
        list-style-type: none;
        padding: 0;
    }

    li {
        background-color: #f9f9f9;
        margin: 8px 0; 
        padding: 10px;
        border: 1px solid #ccc;
    }
</style>
</head>
<body>
    <h1>요소를 동적으로 추가하기</h1>
    <button onclick="addItem()">아이템 추가</button>
    <br>
    <ul id="myList">
        <li>아이템1</li>
    </ul>

    <script>
        let count = 1;
        function addItem() {
            let newItem = document.createElement("li");
            newItem.textContent = `새로운 아이템 ${++count}`; // 전위 연산자 
            // text.Content -> innerHTML로 사용가능
            let ulList = document.querySelector("#myList");
            ulList.append(newItem);
        }

    </script>
</body>
</html>

 

 

시나리오 코드 - 노드 삭제하기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<style>
    ul {
        list-style-type: none;
        padding: 0;
    }

    li {
        background-color: #f9f9f9;
        margin: 8px 0; 
        padding: 10px;
        border: 1px solid #ccc;
    }
</style>
</head>
<body>
    <h1>요소를 동적으로 삭제하기</h1>
    <button onclick="removeItem()">아이템 삭제</button>
    <br>
    <ul id="myList">
        <li>아이템1</li>
        <li>아이템2</li>
        <li>아이템3</li>
    </ul>

    <script>
        // 버튼 눌렀을 때, 마지막 요소를 삭제
        function removeItem() {
            // 1. 요소 들고오기
           let list = document.querySelector("#myList");

           // 2. 마지막 자식요소가 있을 경우, 삭제 (ul의 요소 : li,li,li) - 마지막 자식요소 가져오기
            let lastChile = list.lastElementChild;

            // 3. 삭제처리 : 해당 요소에 removeChile 메서드를 사용. 매개변수는 해당 노드를 넣어준다.
           if(lastChile != null) {
            // lastChile 요소가 있다면 true 반환, 없다면 false 반환
            list.removeChild(lastChile);
           } else {
            alert("더 이상 자식요소가 존재하지 않습니다.");
           }

        }

    </script>
</body>
</html>

 

자바스크립트 속성을 통해서 이벤트 리스너 등록하기
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      ul {
        list-style-type: none;
        padding: 0;
      }

      li {
        background-color: #f9f9f9;
        margin: 8px 0;
        padding: 10px;
        border: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <h1>요소를 동적으로 삭제하기 2</h1>
    <button>아이템 삭제</button>
    <br />
    <ul id="myList">
      <li>아이템 1</li>
      <li>아이템 2</li>
      <li>아이템 3</li>
    </ul>

    <script>
      let btn = document.getElementsByTagName("button");
      console.log(btn);
      btn[0].onclick = function () {
        // 1. 요소 들고 오기 (노드)
        let list = document.querySelector("#myList");

        // 2. 마지막 자식이 있을 경우 삭제 합니다. ul -> li , li, li - 마지막 자식 요소 가져오기
        let lastChild = list.lastElementChild;

        // 3. 삭제 처리 --> 해당 요소에 removeChild 메서드를 사용 , 매개변수는 해당 노드를 넣어 주면 된다.
        if (lastChild != null) {
          // lastChild 요소가 있으면 true 반환 , 없으면 false 반환
          list.removeChild(lastChild);
        } else {
          alert("더이상 자식이 존재하지 않습니다.");
        }
      };
    </script>
  </body>
</html>

'JS' 카테고리의 다른 글

JS 이벤트 처리 - forms  (0) 2024.08.01
JS 이벤트 처리 - addEventListener  (0) 2024.07.26
웹 페이지 렌더링 과정  (0) 2024.07.23
Browser Object Model  (0) 2024.07.23
Document Object Model  (0) 2024.07.23