Programming Language/Javascript, ...

[JavaScript] 이벤트

Ma_Sand 2022. 4. 25. 02:32
반응형

이벤트의 종류

1. 고전 이벤트 모델(기본)

   : 요소객체를 가져와 해당 요소객체에 이벤트 속성으로 접근한 후에 이벤트 핸들러를 연결한다.

  - 이벤스 속성에 null을 대입하여 이벤트를 제거할 수 있다.

  - 동일한 이벤트를 여러 번 사용할 수 없고, 나중에 작성된 이벤트로 덮어쓰기가 된다.

<button id="btn1">고전 이벤트 버튼1</button>
<button id="btn2">고전 이벤트 버튼2</button>

<div id="antique" class="zone"></div>

<script>
    var antique = document.getElementById("antique");
    var btn1 = document.getElementById("btn1");

    // 버튼1 클릭했을 때 메세지 넣기
    btn1.onclick = function(){
        antique.innerHTML += "버튼 클릭! <br>";
    }
    
    // 버튼2 클릭했을 때 버튼1의 이벤트를 삭제하기
    document.getElementById("btn2").onclick = function(){
        document.getElementById("btn1").onclick = null;
        // 클릭 후 버튼1을 클릭해도 메세지가 안넣어진다.
    }

    document.getElementById("btn1").onmouseover = function(){
        antique.style.backgroundColor="aqua";
    }
</script>

 

 

 

2. 인라인 이벤트 모델

   : 요소 내부에 직접적으로 이벤트 속성을 제시하여 실행할 내용을 정의한다.

  - 주로 script 태그에 정의돼있는 함수를 호출하는 방식으로 사용한다.

  - 이 모델은 구문이 길어지고 복잡해보여 잘 사용하지 않는다.

<button onclick="click();">버튼 누르기</button>
<button onclick="document.getElementById('zone').innerHTML += '첫 번째 버튼 클릭 <br>';">버튼 클릭</button>
<div id="zone" class="zone"></div>
<script>
    function click(){
        document.getElementById("zone").innerHTML += "첫 번째 버튼 클릭 <br>";
    }
</script>

 

 

 

3. 표준 이벤트 모델(addEventListener)

  - 동일한 이벤트를 여러 번 사용할 수 있다.

  - 이벤트 대상 요소객체.addEventListener("이벤트명", 이벤트 핸들러);

// 마우스 포인터가 버튼 안으로 들어가는 순간 발생하는 이벤트(mouseenter)
btn3.addEventListener("mouseenter", function(){
    btn3.style.backgroundColor="pink";
});

// 마우스 포인터가 버튼 밖으로 나가는 순간 발생하는 이벤트(mouseout)
btn3.addEventListener("mouseout", function(){
    btn3.style.backgroundColor="lightgrey";
    btn3.style.border="1px solid grey";
});

// 마우스로 버튼을 눌렀을 때 발생하는 이벤트
btn3.addEventListener("mousedown", function(){
    btn3.style.backgroundColor="yellow";
})

 

 

 

 

이벤트가 발생한 요소객체에 접근하기

<button id="btn4">고전이벤트방식</button>
<button id="btn5">표준이벤트방식</button>
<button onclick="test(this);">인라인이벤트방식</button>

<script>
    // 고전 이벤트 모델
    document.getElementById("btn4").onclick=function(e){  // 이벤트 핸들러

        window.event.target.style.backgroundColor="lightpink";
        e.target.innerHTML = "버튼 클릭됨";
        this.style.color="hotpink";

        alert(this.id);
    }

    // 표준 이벤트 모델
    document.getElementById("btn5").addEventListener("click", function(e){
        console.log(window.event.target);
        console.log(e.target);
        console.log(this);
    });

    // 인라인 이벤트 모델
    function test(e){
        console.log(window.event.target);
        console.log(this);  // Window 객체 정보를 가지고 있음
    }
</script>

 

 

 

 

태그별로 기본적으로 가지고 있는 이벤트 제거하기

  - 태그별로 기본적으로 가지고 있는 요소

    : a 태그는 a 태그 클릭 시에 href에 제시된 url을 요청하는 기본 이벤트를 가지고 있다.

       form 태그 내의 submit 버튼은 submit 버튼 클릭 시에 사용자가 입력한 정보들을 action에 제시돼있는

       url에 제출하며 요청하는 이벤트를 가지고 있다.

 

  - 태그 내에 기본적으로 설정된 이벤트를 제거할 때 이벤트 핸들러의 return값을 false로 리턴하면

      기본 이벤트가 실행되지 않는다.

<a href="https://www.daum.net" onclick="alert('잠깐!');">다음으로 가기</a> <br>
<a href="http://www.daum.net" onclick="again();">또 다음으로 가기</a>
<script>
    function again(){  
        alert("기다려!");
        return false;
        // 스크립트 내에서 return false 하면 어차피 a태그로 돌아가기 때문에 url이 실행된다.
    }
</script>
반응형