티스토리 뷰

자바스크립트에서 클라이언트가 버튼을 클릭했거나, 입력 창에 값을 입력하는 등의 동작을 했을 경우, 이벤트 리스너를 활용하여 해당 이벤트에 맞는 동작을 수행하도록 구현할 수도 있다.

 

이벤트 리스너를 사용하는 방법은 크게 두가지가 있다.

 

1.

var addBtn = document.querySelector("#add"); //버튼의 id 값

addBtn.addEventListener("click", addList);  // add 버튼을 클릭 했을 때, addList 함수 호출

 

2. 

var addBtn = document.querySelector("#add"); //버튼의 id 값

addBtn.click = addList;

 

바로 예제를 한번 확인해보자.


예제: 버튼 클릭 이벤트를 사용하여 입력 항목을 리스트에 추가하기

 

◎input.css

* {
  box-sizing:border-box;
}
#wrapper {
  width:600px;
  margin:0 auto;
}
h2 {
  text-align:center;
}
form {
  background-color:#007acc;
  padding:30px 40px;
  color:white;
  text-align:center;
}
input {
  border:none; 
  width:440px;
  padding:10px;
  float:left;
  font-size:16px;
}
.addBtn {
  padding:10px;
  width:50px;
  border:none;
  background-color:#fff;
  box-shadow:1px 2px 4px #167dae;
  color:#555; 
  text-align:center;
  font-size:14px;
  cursor:pointer;
  transition:0.3;
}
form::after { /**form 태그 내부 버튼이 눌려진 후**/ 
  content:"";
  display:table;
  clear:both;
}

◎list.css

form::after {
  content:"";
  display:table;
  clear:both;
}
ul{
  margin:0;
  padding:0;
  list-style: none;
}
ul li{
  cursor:pointer;
  position:relative;
  padding:12px 8px 12px 40px;
  background: #eee;
  font-size:18px;
  transition: 0.2s;
}
ul li:nth-child(odd) {
  background-color:#f9f9f9;
}
ul li:hover {
  background-color:#ddd;
}
.close {
  position:absolute;
  right:0;
  top:0;
  padding:12px 16px;
  border:none;
  background:rgba(255,255,255,0)
}
.close:hover {
  background-color:#007acc;
  color:white;
}

◎checklist-1.js

var itemList = [];

var addBtn = document.querySelector("#add");

addBtn.addEventListener("click", addList);  // add 버튼을 클릭 했을 때, addList 함수 호출

function addList() {
	var item = document.querySelector("#item").value; //텍스트 필드 값을 저장
	
	if(item != null) {
		itemList.push(item); // itemList의 맨 뒤에 item 값을 추가
		document.querySelector("#item").value = "";  // input 내의 값을 초기화
		document.querySelector("#item").focus(); // input 필드에 자동 포커스
	}
	showList();
}

function showList() {
	var list = "<ul>";
	for (var i = 0; i < itemList.length; i++){
		list = list + "<li>" + itemList[i] + "</li>";
	}
	list = list + "</ul>";
	
	document.querySelector("#itemList").innerHTML = list;
	
}

◎index.html

<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width"> <!-- 요청한 기기의 가로 사이즈 -->
	<title>여행 준비물 점검 목록</title>
	<link rel="stylesheet" href="css/input.css">
	<link rel="stylesheet" href="css/list.css">
</head>
<body>
	<div id="wrapper">
		<h2>여행 준비물 점검 목록</h2>
		<form>
			<input type="text" id="item" autofocus="true">
			<button type="button" id="add" class="addBtn">추가</button>
		</form>
		<div id="itemList"></div>
	</div>    
	<script src = "js/checklist-1.js"> </script>
</body>
</html>

위와 같이 추가 버튼을 눌렀을 때, 리스트가 추가되는 것을 확인할 수 있다.

Comments