오뚝이개발자

[JS]HTML과 JS의 만남 : 이벤트 본문

Front-end/JS

[JS]HTML과 JS의 만남 : 이벤트

땅어 2020. 8. 30. 22:36
728x90
300x250

 

본 글은 유튜버 생활코딩님의 WEB2 JavaScript 강의를 듣고 정리한 것이다. 

웹페이지에선 다양한 일들이 발생할 수 있다. 예컨대, 클릭이나 텍스트입력과 같은 일들이다. 나열하자면 무수히 많은데 이러한 것들을 이벤트라고한다. JS를 사용하면 이들 이벤트가 발생하였을 때 각각 특정한 동작을 하도록 지정할 수 있다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="button" value="hi" onclick="alert('hi')">
</body>
</html>

위 코드는 hi라는 버튼을 만들어 이를 클릭했을 때 hi라는 alert 메시지가 뜨도록 한다.

코드를 실행시키고 크롬으로 열어보면 위와 같이 hi 버튼이 만들어진다. 이를 클릭하면 아래와 같은 메시지가 뜬다.

이제 다른 이벤트도 다뤄보도록 하자. 코드에 아래와 같이 한 줄을 추가해보자.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="button" value="hi" onclick="alert('hi')">
    <input type="text" onchange="alert('changed')">
</body>
</html>

그럼 아래와 같이 hi 버튼 옆에 텍스트 창이 뜰 것이다. 위 코드와 같이 type 속성을 text로 주면 입력할 수 있는 텍스트 상자를 만든다. 뒤의 onchange는 텍스트 박스 안의 내용이 바뀌게 되면~ 이라는 뜻이고 이 때 changed라는 alert 메시지를 출력하도록 하는 것이다. 아무런 내용이 없는 상태에서 무언가 텍스트를 입력하고 커서로 빈 공간을 누르면 메시지가 뜰 것이다.

이제 새로운 이벤트를 추가해 코드를 아래와 같이 바꾸어 보자.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="button" value="hi" onclick="alert('hi')">
    <input type="text" onchange="alert('changed')">
    <input type="text" onkeydown="alert('key down!')">
</body>
</html>

onkeydown이라는 이벤트가 추가되었다. 해당 이벤트는 키보드 입력이 주어지는 것을 의미한다. 코드를 실행시키고 크롬으로 열면 아래와 같이 된다.

해당 칸에 아무 키나 입력하면 key down! 메시지가 뜬다.

위에서 언급한 onclick, onchange, onkeydown 이러한 것들이 이벤트를 일컫는 속성이다. 다양한 이벤트들이 있으니 구글링을 해보면 도움이 될 것이다.

728x90
300x250
Comments