Frontend/JavaScript
[생활코딩][웹브라우저JS] - 이벤트 기본동작 취소
blueprint-12
2022. 2. 15. 18:26
웹브라우저의 구성요소들은 각각 기본적인 동작 방법을 가지고 있다.
- 텍스트 필드에 포커스를 준 상태에서 키보드를 입력하면 텍스트가 입력된다.
- 폼에서 submit 버튼을 누르면 데이터가 전송된다.
- a 태그를 클릭하면 href 속성의 URL로 이동한다.
이러한 기본적인 동작들을 기본 이벤트라고 하는데 사용자가 만든 이벤트를 이용해서 이러한 기본 동작을 취소할 수 있다.
inline 방식의 경우
이벤트의 리턴값이 false이면 기본 동작이 취소된다.
<body>
<!-- 인라인 방식일 때 -->
<p>
<label>prevent event on</label
><input id="prevent" type="checkbox" name="eventprevent" />
</p>
<p>
<!-- 만일 id가 prevent인 체크박스의 값이 true(checked)라면 return false -->
<a
href="http://opentutorials.org"
target="_blank"
onclick="if(document.getElementById('prevent').checked) return false;"
>opentutorials</a>
</p>
<p>
<form action="http://opentutorials.org" onsubmit="if(document.getElementById('prevent').checked) return false;">
<input type="submit" />
</form>
</p>
</body>
- 위의 코드는 체크박스의 체크 여부에 따라서 a태그와 form태그의 기본동작을 막는 기능을 한다.
- 참고로 onclick 내부의 JS코드 중 ~.checked 부분은 체크박스의 상태가 true인 것과 같은 뜻이다.
property 방식의 경우
인라인 방식과 마찬가지로 리턴 값이 false이면 기본동작이 취소된다.
<body>
<p>
<label>prevent event on</label><input id="prevent" type="checkbox" name="eventprevent" value="on" />
</p>
<p>
<a href="http://opentutorials.org">opentutorials</a>
</p>
<p>
<form action="http://opentutorials.org">
<input type="submit" />
</form>
</p>
<script>
//각각의 객체에 이벤트 프로퍼티를 지정하고 그곳에 함수를 대입
document.querySelector('a').onclick = function(event){
if(document.getElementById('prevent').checked)
return false;
};
document.querySelector('form').onclick = function(event){
if(document.getElementById('prevent').checked)
return false;
};
</script>
</body>
addEventListener 방식의 경우
이 방식에서는 이벤트 객체의 preventDefault 메소드를 실행하면 기본 동작이 취소된다.
- event.preventDefault();
<script>
document.querySelector('a').addEventListener('click', function(event){
if(document.getElementById('prevent').checked)
event.preventDefault();
});
document.querySelector('form').addEventListener('submit', function(event){
if(document.getElementById('prevent').checked)
event.preventDefault();
});
</script>
- addEventListener를 통해 이벤트핸들러를 설치했을 때는 리턴값으로 하는 것이 아니라 이벤트 핸들러의 2번째 인자인 함수에게 전달된 event객체가 가지고 있는 메소드를 활용하는 것이다.
참고 ) ie9 이하 버전에서는 event.returnValue를 false로 해야 한다.
- event.returnValue는 MDN에서 Deprecated(중요도가 떨어져 더 이상 사용되지 않고 앞으로는 사라지게 될 컴퓨터 시스템 기능 등)으로 서술된 기능이라서 크게 신경쓰지 않아도 된다.
이벤트 관련 상세한 설명이 있는 참고 사이트 :
https://poiemaweb.com/js-event
Event | PoiemaWeb
이벤트(event)는 어떤 사건을 의미한다. 브라우저에서의 이벤트란 예를 들어 사용자가 버튼을 클릭했을 때, 웹페이지가 로드되었을 때와 같은 것인데 이것은 DOM 요소와 관련이 있다. 이벤트가 발
poiemaweb.com