Javascript :: 이벤트

김병철·2022년 11월 22일
0

JavaScript

목록 보기
9/11

이벤트

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

요소 객체를 가져와서 해당 요소 객체에 이벤트 속성에 접근한 후 이벤트 핸들러를 연결하는 방식

이벤트를 제거할 수 있다.(이벤트 속성에 null 대입)

버튼1, 버튼2를 누르면 area div영역의 innerHTML 속성을 변경한다.

  • 코드 :
<button id="btn1">버튼 1</button>
<button id="btn2">버튼 2</button>

<div class="area" id="area1"></div>
<script>
    var area1 = document.getElementById("area1");

    // var btn1 = document.getElementById("btn1");
    // btn1.onclick
    document.getElementById("btn1").onclick = function(){
        area1.innerHTML = "버튼이 클릭되었습니다<br>";
    }
    document.getElementById("btn2").onclick = function(){
        area1.innerHTML = "두번째 버튼이 클릭되었습니다<br>";
        // document.getElementById("btn1").onclick = null;
        // 윗 줄을 넣으면 이벤트가 제거된 후 btn1을 클릭하면 아무것도 실행되지 않는다 null로 바꿔서
    }
</script>
  • 출력 :

버튼 1 클릭 시

버튼 2 클릭 시


인라인 이벤트 모델

요소 내부에 직접적으로 이벤트 속성을 제시해서 실행할 내용을 정의하는 방식

주로 script 태그 내에 정의된 함수를 호출하는 방식을 선호한다.

  • 코드 :
<button onclick="inlineEventTest();">인라인이벤트1</button>
<!-- 잘 사용하지 않는 버튼2 방식. 가독성 좋지 않음-->
<button onclick="document.getElementById('area2').innerHTML = '인라인 버튼2이 눌렸습니다.'">인라인이벤트2</button>
<div class="area" id="area2"></div>

<script>
    function inlineEventTest(){
        document.getElementById("area2").innerHTML = "인라인 버튼1이 눌렸습니다.";
    }
</script>
  • 출력 :

인라인이벤트1 클릭 시

인라인이벤트2 클릭 시


표준 이벤트 모델(addEventListener)

  • 코드 :
<button id="btn3">mousenter</button>

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

    // 이벤트를 걸 요소객체.addEveneListener("이벤트명", 이벤트핸들러);
    btn3.addEventListener("click", function(){
        alert("표준이벤트 모델 실행");
    })

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

</script>
  • 출력 :

평상시 버튼와 마우스를 올렸다가 마우스가 버튼 밖으로 다시 나갔을 경우

마우스를 올렸을 경우 버튼

마우스 클릭 시 팝업 창


현재 이벤트가 발생한 해당 요소객체에 접근하는 방법

고전 이벤트 방식

  • 코드 :
<button id="btn4">고전 이벤트 방식</button>
<script>
    // 고전 이벤트 모델 방식
    document.getElementById("btn4").onclick = function(e){
        console.log(window.event);
        window.event = e;
        console.log(e);

        // 이벤트가 발생한 요소에 대해 알려면?
        // window.event.target / e.target / this
        console.log(window.event.target);
        console.log(e.target);
        console.log(this);

        window.event.target.style.backgroundColor="yellow";
        e.target.innerHTML = "버튼클릭됨";
        this.style.color = "hotpink";
    }
</script>
  • 출력 :

고전 이벤트 방식 버튼 클릭 후 버튼 모양

콘솔 로그 확인

표준 이벤트 방식

  • 코드 :
<button id="btn5">표준 이벤트 방식</button>
<script>
    // 표준 이벤트 모델 방식
    document.getElementById("btn5").addEventListener("click", function(e){
        window.event.target.style.backgroundColor="violet";
        e.target.innerHTML = "누름";
        this.style.color="red";
        this.style.border = "none";
        setTimeout(function(){
            // e.target.innerHTML = "표준 이벤트 방식";
            // this.style.color="black";
            // this.style.backgroundColor="cornflowerblue";
            // this.style.border = "rgb(188, 212, 219)";
        }, 1000);
    })
</script>
  • 출력 :

표준 이벤트 방식 버튼 클릭 후 버튼 모양

인라인 이벤트 방식

  • 코드 :
<button onclick="test2();">인라인 이벤트 방식</button>
<script>
    // 인라인 이벤트 모델 방식
    function test2(){
        // 호출 시 매개변수를 같이 넣지 않았기 때문에 오류 발생
        // 매개변수를 넣더라도 표준, 고전방식과 같이 사용할 수 
        // console.log(e.target); //사용불가
        // this 키워드 사용 시 window객체를 가리키게 된다.
        // console.log(this); 사용불가
        // 때문에 위 두 방식과 다르게 인라인 모델 방식에서는 window.event.target만 가능
        console.log(window.event.target);
    }
</script>
  • 출력 :

인라인 이벤트 방식 버튼 클릭 후 콘솔 로그


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

기본적으로 이벤트를 가지고 있는 요소

  • a태그 : 클릭 시 href에 제시된 url 요청을 하는 기본 이벤트 보유
  • form 태그 내의 submit 버튼 : 클릭 시 사용자가 입력한 정보들을 action에 제시된 url로 제출하며 요청하는 이벤트 보유
    (태그 내 기본적으로 설정된 이벤트를 제거하려면)
  • 이벤트 핸들러의 return 값을 false로 리턴하면 된다.

기본 이벤트가 있는 요소에 onclick 이벤트 속성을 부여하면 onclick이 먼저 수행된다.

기본 이벤트가 수행되지 않게 해주려면 return false를 작성한다.

<a href="https:www.naver.com" target="_blank" onclick="test4();">Naver로 이동~</a>
<script>
    function test4(){
        alert("이동 하지 않아야하는데 이동한다.");
        return false;       // 함수 안에서 return false; 를 해도 기본 이벤트를 막을 수 없다.
    }
</script>

위 링크를 누르면 해당 페이지로 이동한다.

<a href="https:www.naver.com" target="_blank" onclick="test4(); return false;">Naver return false</a>
<script>
    function test4(){
        alert("이동 하지 않는다.");
        return false;       // 함수 안에서 return false; 를 해도 기본 이벤트를 막을 수 없다.
    }
</script>

위 링크를 누르면 링크로 이동하지 않는다.

profile
keep going on~

0개의 댓글