1. Javascript
- 1995년 넷스케이프 회사(현제는 없어짐, 문닫기 직전, ECMA사로 넘김)에서 개발되고 Netscape Navigator 2.0 브라우저에 최초로 탐재되어 웹 프로그래밍의 개념을 창시한 언어이다.
1) 모던 자바스크립트
모던 JavaScript 튜토리얼
ko.javascript.info
- 자바 스크립트의 기본 개념 및 고급 개념을 다루는 사이트이다.
- 자바스크립트 문법을 공부할 수 있다.
2. Javascript 언어
1) 자바스크립트 코드의 위치
[1] html 태그의 이벤트 리스너 속성에 작성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 리스너 속성에 자바스크립트 코드</title>
</head>
<body>
<h3>마우스 올려 보세요</h3>
<hr>
<img src="media/apple.png" alt="이미지" onmouseover="this.src='media/banana.png'"
onmouseout="this.src='media/apple.png'">
<!--onclick: 이벤트 리스너 속성, this.src='사진경로': 자바스크립트 코드-->
</body>
</html>
- 사과 이미지 위에 마우스를 올리면 바나나 이미지로, 내리면 다시 사과 이미지로 바뀌도록 하는 코드이다.
- onmouseover: 마우스가 올라갈 때 발생하는 이벤트 리스너 속성
- onmouseout: 마우스가 내려갈 때의 리스너 속성
- 이미지가 보이기 위해 html 파일이 있는 폴더 밑에 media 폴더를 만들고 banana.png, apple.png를 두어야 한다.
--> 결과
[2] <script>태그에 자바스크립트 코드 작성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>script 태그에 자바스크립트 작성</title>
<script>
function over(obj) {//obj는 전달받은 img 태그를 가리킴
obj.src = "media/banana.png";
}
function out(obj) {
obj.src = "media/apple.png";
}
</script>
</head>
<body>
<h3>마우스 올려 보세요</h3>
<hr>
<img src="media/apple.png" alt="이미지" onmouseover="over(this)" onmouseout="out(this)">
<!--this는 현재 img 태그를 가리키는 자바스크립트 키워드-->
</body>
</html>
- script 태그에 자바스크립트 코드를 작성한 것이다.
--> 결과
결과는 [1]하고 같다.
[3] 자바스크립트 코드를 별도 파일에 작성
1) lib.js
function over(obj) {
obj.src = "media/banana.png";
}
function out(obj) {
obj.src = "media/apple.png";
}
2) ex06-3.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>외부 파일에 자바스크립트 작성</title>
<script src="lib.js">
</script>
</head>
<body>
<h3>마우스 올려 보세요</h3>
<hr>
<img src="media/apple.png" alt="이미지" onmouseover="over(this)" onmouseout="out(this)">
</body>
</html>
- 자바스크립트 코드를 확장자가 .js인 별도의 파일로 저정하고 <script>태그의 src 속성으로 불러 사용할 수 있다.
--> 결과
결과는 [1]하고 같다.
[4] URL부분에 자바스크립트 코드 작성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>URL에 자바스크립트 작성</title>
</head>
<body>
<h3>링크의 href에 자바스크립트 작성</h3>
<hr>
<a href="javascript:alert('클릭하셨어요?')">
클릭해보세요</a>
</body>
</html>
- <a>태그의 href 속성에 자바스크립트를 작성할 수 있다.
--> 결과
2) 자바스크립트로 html콘텐츠 출력
[1] document.write
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document.write() 활용</title>
</head>
<body>
<h3>document.write() 활용</h3>
<hr>
<script>
document.write("<h3>Welcome!</h3>");
document.write("2 + 5 는 <br>");
document.write("<mark>7 입니다.</mark>");
</script>
</body>
</html>
- 자바스크립트 코드로 html 콘텐츠를 웹 페이지에 직접 삽입해 바로 브라우저에 출력할 수 있다.
- document.write()나 document.writeln()을 사용한다.
--> 결과
3. Javascript 코어 객체와 배열
1) 리터럴 표기법으로 객체만들기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>리터럴 표기법으로 객체 만들기</title>
<script>
//사용자 객체 만들기
let account = {
// 프로퍼티 생성 및 초기화
owner: "황기태", // 계좌 주인
code: "111", // 계좌 코드
balance: 35000, // 잔액 프로퍼티
// 메소드 작성
inquiry: function () { return this.balance; }, // 잔금 조회
deposit: function (money) { this.balance += money; }, // 저금. money 만큼 저금
withdraw: function (money) { // 예금 인출, money는 인출하고자 하는 액수
// money가 balance보다 작다고 가정
this.balance -= money;
return money;
}
};
</script>
</head>
<body>
<h3>리터럴 표기법으로 사용자 객체 만들기</h3>
<hr>
<script>
document.write("account : ");
document.write(account.owner + ", ");
document.write(account.code + ", ");
document.write(account.balance + "<br>");
account.deposit(10000); // 10000원 저금
document.write("10000원 저금 후 잔액은 " + account.inquiry() + "<br>");
account.withdraw(5000); // 5000원 인출
document.write("5000원 인출 후 잔액은 " + account.inquiry() + "<br>");
</script>
</body>
</html>
- account객체는 중괄호를 이용해 프로퍼티와 메소드를 한 번에 작성할 수 있다.
- 이 방법을 리터럴 표기법이라고 한다. 메소드와 프로퍼티가 블록 안에 모두 만들어져 가독성이 높다.
--> 결과
4. HTML DOM과 Document
- HTML DOM 객체: 각 HTML 태그를 하나의 객체로 만든다.
- DOM의 목적: HTML 태그가 출력된 모양과 콘텐츠를 제어하기 위해서이다.
- DOM 트리: HTML태그의 포함관게이다.
- DOM 트리의 특징
1) DOM 트리의 루트는 document객체이다.(html 위에 있음), 하지만 document 객체는 dom 객체가 아니다.
2) DOM트리는 html 태그의 호마관계에 따라 부모 자식 관계로 구성된다. html 태그안에 head와 body가 있으면 html 객체는 head와 body를 자식 객체로 가진다.
1) DOM객체의 구조: p객체 사례
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML DOM 트리</title>
</head>
<body>
<h3>DOM 객체 p의 프로퍼티, 스타일, 이벤트 리스너</h3>
<hr>
<p id="firstP" style="color:blue; background:yellow" onclick="this.style.color='teal'">이것은
<span style="color:red">문장입니다.</span>
</p>
<script>
let p = document.getElementById("firstP");//id가 firstP인 태그의 DOM객체 찾기
let text = "p.id = " + p.id + "\n";
text += "p.tagName = " + p.tagName + "\n";
text += "p.innerHTML = " + p.innerHTML + "\n";
text += "p.style.color = " + p.style.color + "\n";
text += "p.onclick = " + p.onclick + "\n";
text += "p.childElementCount = " + p.childElementCount + "\n";
text += "너비 = " + p.offsetWidth + "\n";
text += "높이 = " + p.offsetHeight + "\n";
alert(text);
</script>
</body>
</html>
- DOM 객체 p의 프로퍼티와 이벤트 리스너 그리고 CSS3 스타일 시트를 접근한 사례를 보여준다.
--> 결과
2) 자바스크립트로 <span>태그의 css3 스타일 동적변경
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSS 스타일 동적 변경</title>
<script>
function change() {
//let span = document.getElementById("mySpan"); // id가 mySpan인 객체 찾기
let span = document.querySelector("#mySpan");//css셀렉터만 옴
span.style.color = "green"; // 글자 색 green
span.style.fontSize = "30px"; // 글자 크기는 30픽셀
span.style.display = "block"; // 블록 박스로 변경
span.style.width = "6em"; // 박스의 폭. 6 글자 크기
span.style.border = "3px dotted magenta"; // 3픽셀 점선 magenta 테두리
span.style.margin = "20px"; // 상하좌우 여백 20px
}
</script>
</head>
<body>
<h3>CSS 스타일 동적 변경</h3>
<hr>
<p style="color:blue">이것은
<span id="mySpan" style="color:red">문장입니다. </span>
</p>
<input type="button" value="스타일변경" onclick="change()">
</body>
</html>
- 자바스크립트 코드로 id속성 값이 "mySpan"인 <span>태그를 찾아 박스 유형, 글자크기, 글자색, 테두리 등을 변경한다.
--> 결과
3) innerHTML을 이용한 HTML 콘텐츠 동적 변경
- DOM 객체의 innerHTML 프로퍼티는 시작태그와 종료 태그 사이에 있는 HTML콘텐츠를 나타내는 문자열 정보이다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>innerHTML 활용</title>
<script>
function change() {
let p = document.getElementById("firstP");
p.innerHTML = "나의 <img src='media/puppy.png'> 강아지";
}
</script>
</head>
<body>
<h3>innerHTML 활용 : 아래 글자에 클릭하면 예쁜 강아지가 보입니다.</h3>
<hr>
<p id="firstP" style="color:blue" onclick="change()">여기에
<span style="color:red">클릭하세요</span>
</p>
</body>
</html>
- innerHTML 프로퍼티를 이용하면 <p>태그에 있는 html 텍스트를 읽을 수 있다.
- 이 코드문은 innerHTML 프로퍼티를 이용해 <p> 태그의 콘텐츠를 변경할 수 있따.
--> 결과
4) this
- this: 객체 자신을 가리키는 자바스크립트로 DOM 객체에서 객체 자신을 가리키는 용도로 사용된다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>this 활용</title>
<script>
function change(obj, size, color) {
obj.style.color = color;
obj.style.fontSize = size;
}
</script>
</head>
<body>
<h3>this 활용</h3>
<hr>
<button onclick="change(this, '30px', 'red')">버튼</button>
<button onclick="change(this, '30px', 'blue')">버튼</button>
<div onclick="change(this, '25px', 'orange')">
여기 클릭하면 크기와 색 변경
</div>
</body>
</html>
- 버튼이나 <div> 텍스트를 클릭시 this를 이용해 자신의 글자색과 크기를 변경한다.
--> 결과
5) document
<!DOCTYPE html>
<html>
<head id="myHead">
<meta charset="UTF-8">
<title>document 객체의 주요 프로퍼티</title>
<script>
let text = "문서 로딩 중일 때 readyState = " + document.readyState + "\n";
</script>
</head>
<body style="background-color:yellow; color:blue; direction:rtl" onload="printProperties()">
<h3>document의 주요 프로퍼티</h3>
<hr>
<a href="http://www.naver.com">네이버 홈페이지</a>
<div>이곳은 div 영역입니다.</div>
<input id="input" type="text" value="여기 포커스가 있습니다">
<script>
// 문서가 완전히 로드(출력)되었을 때, 현재 document의 프로퍼티 출력
function printProperties() {
document.getElementById("input").focus(); // <input> 태그에 포커스를 줌
text += "1. location =" + document.location + "\n";
text += "2. URL =" + document.URL + "\n";
text += "3. title =" + document.title + "\n";
text += "4. head의 id =" + document.head.id + "\n";
text += "5. body color =" + document.body.style.color + "\n";
text += "6. domain =" + document.domain + "\n";;
text += "7. lastModified =" + document.lastModified + "\n";
text += "8. defaultView = " + document.defaultView + "\n";
text += "9. 문서의 로드 완료 후 readyState = " + document.readyState + "\n";
text += "10. referrer = " + document.referrer + "\n";
text += "11. activeElement = " + document.activeElement.value + "\n";
text += "12. documentElement의 태그 이름 = " + document.documentElement.tagName + "\n";
alert(text);
}
</script>
</body>
</html>
- html 페이지를 로드후 document 객체의 프로퍼티 값을 읽어 html페이지의 다양한 속성들을 경고창에 출력한다.
--> 결과
5) 태그이름으로 DOM 객체 찾기, getElementsByTagName()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document.getElementsByTagName()</title>
<script>
function change() {
//let spanArray = document.getElementsByTagName("span");
// for (let i = 0; i < spanArray.length; i++) {
// let span = spanArray[i];
// span.style.color = "orchid";
// span.style.fontSize = "20px";
// }
let spanArray = document.querySelectorAll("span");
for (let span of spanArray) {
span.style.color = "orchid";
span.style.fontSize = "20px";
}
}
</script>
</head>
<body>
<h3>내가 좋아하는 과일
<button onclick="change()">누르세요</button>
</h3>
<hr>
저는 빨간 <span>사과</span>를 좋아해서
아침마다 한 개씩 먹고 있어요. 운동할 때는 중간 중간에
<span>바나나</span>를 먹지요. 탄수화물 섭취가 빨라
힘이 납니다. 또한 달콤한 향기를 품은 <span>체리</span>와
여름 냄새 물씬 나는 <span>자두</span>를 좋아합니다.
</body>
</html>
- document객체의 getElementsByTagName() 메소드를 호출시 동일한 HTML 태그 이름을 가진 DOM 객체들을 모두 찾아 컬렉션을 만들어 리턴한다.
- getElementsByTagName()뿐만 아니라 querySelector혹은 querySelectorAll을 쓸 수 있다. querySelector는 CSS선택자에 매치되는 하나 이상의 element중 첫번째 항목을 반환해준다.
- for문이 아닌 for ...of문을 이용할 수 있다.
--> 결과
6) class 속성으로 DOM 객체 찾기, getElementsByClassName()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document.getElementsByClassName()</title>
<script>
function viewPlace() {
//let tagArray = document.getElementsByClassName("place");
// for (let i = 0; i < tagArray.length; i++) {
// let tag = tagArray[i];
// tag.style.color = "orchid";
// tag.style.fontSize = "20px";
// tag.style.textDecoration = "underline";
// }
let tagArray = document.querySelectorAll(".place");
for (let tag of tagArray) {
tag.style.color = "orchid";
tag.style.fontSize = "20px";
tag.style.textDecoration = "underline";
}
}
function viewFood() {
//let tagArray = document.getElementsByClassName("food");
// for (let i = 0; i < tagArray.length; i++) {
// let tag = tagArray[i];
// tag.style.color = "darkcyan";
// }
let tagArray = document.querySelectorAll(".food");
for (let tag of tagArray) {
tag.style.color = "darkcyan";
}
}
</script>
</head>
<body>
<h3>가고 싶은 곳 먹고 싶은 것</h3><br>
<button onclick="viewPlace()">가고 싶은 곳</button>
<button onclick="viewFood()">먹고 싶은 것</button>
</h3>
<hr>
<p><span class="place">제주도</span>에 가서 <span class="food">흑돼지</span>를 먹고 싶고요.
<span class="place">독도</span>에 가서 <span class="food">독도 새우</span>도 먹고 싶어요. 제일 가고 싶은 곳 <span class="place">부산 자갈치
시장</span>에서 <span class="food">꼼장어 구이</span>도 먹고 싶어요
</p>
</body>
</html>
- getElementsByClassName() 메소드는 동일한 class 이름을 가진 모든 DOM객체를 찾아 컬렉션 형태로 리턴한다.
- querySelector혹은 querySelectorAll를 쓸수 있으며 class이름은 . 을 붙여서 적는다.
--> 결과
7) document.write() 사용시 주의점
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>write()를 잘못 사용하는 예</title>
</head>
<body onclick="document.write('<h3>클릭되었습니다</h3>')">
<h3>write()를 잘못 사용하는 예</h3>
<hr>
<p>웹브라우저의 바탕 아무 곳이나
클릭해보세요.</p>
</body>
</html>
- HTML문서에 텍스트를 추가하기 위해 document.write()를 사용하지만 HTML문서가 로드되어 출력이 모두 이러어지고 나면 document 객체가 닫히기 때문에, 더이상 HTML 텍스트를 출력할 수 없다.
- document 객체가 닫힌 후 document.write()가 실행되면, 브라우저는 document 객체에 담긴 현재 문서를 지우고 빈 document를 새로연다.
--> 결과
8) HTML문서 동적 구성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문서의 동적 구성</title>
<script>
function createDIV() {
let obj = document.getElementById("parent");
let newDIV = document.createElement("div");
//createElement()를 이용해 div태그의 DOM 객체를 생성한다.
newDIV.innerHTML = "새로 생성된 DIV입니다.";
//innerHTML 프로퍼티로 div태그에 HTML 텍스트를 삽입한다.
newDIV.setAttribute("id", "myDiv");
//setAttribute로 div태그에 속성을 추가하거나 CSS3 스타일 시트도 달수 있다.
newDIV.style.backgroundColor = "yellow";
newDIV.onclick = function () {
let p = this.parentElement; // 부모 HTML 태그 요소
p.removeChild(this); // 자신을 부모로부터 제거한다.
};
obj.appendChild(newDIV);//부모의 마지막 자식으로 삽입한다.
}
</script>
</head>
<body id="parent">
<h3>DIV 객체를 동적으로 생성, 삽입, 삭제하는 예제</h3>
<hr>
<p>DOM 트리에 동적으로 객체를 삽입할 수 있습니다.
createElement(), appendChild(),
removeChild() 메소드를 이용하여 새로운 객체를 생성,
삽입, 삭제하는 예제입니다.</p>
<a href="javascript:createDIV()">DIV 생성</a>
<p>
<p>
</body>
</html>
--> 결과
5. 이벤트
- 이벤트: 사용자의 입력행위, 문서나 브라우저의 상태 변화를 브라우저가 자바스크립트 코드에게 알리는 통이징다.
- event listener: 발생한 이벤트에 대처하기 위해 작성된 자바스크립트 코드
1) 이벤트 리스너 작성(HTML 태그에 이벤트 리스너 작성)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML 태그에 리스너 작성</title>
</head>
<body>
<h3>HTML 태그에 리스너 작성</h3>
<hr>
<p onmouseover="this.style.backgroundColor='orchid'" onmouseout="this.style.backgroundColor='white'">
마우스 올리면 orchid 색으로 변경</p>
</body>
</html>
- omouseover리스너는 마우스 커서가 객체 영역 안으로 들어가는 순간 이벤트가 발생한다.
- omouseout리스너는 마우스 커서가 객체 영역 안으로 벗어나는 순간 이벤트가 발생한다.
--> 결과
2) 이벤트 리스너 작성2(이벤트 리스너 프로퍼티에 리스너 등록)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DOM 객체의 이벤트 리스너 프로퍼티에 함수 등록</title>
<script>
let p;
function init() { // 문서가 완전히 로드되었을 때 호출
p = document.getElementById("p");
p.onmouseover = over; // over() 함수를 onmouseover 리스너로 등록
p.onmouseout = out; // out() 함수를 onmouseout 리스너로 등록
}
function over() {//onmouseover 리스너로 over() 함수 등록
p.style.backgroundColor = "orchid";
}
function out() {
p.style.backgroundColor = "white";
}
</script>
</head>
<body onload="init()">
<h3>DOM 객체의 이벤트 리스너 프로퍼티에 함수 등록</h3>
<hr>
<p id="p">마우스 올리면 orchid 색으로 변경</p>
</body>
</html>
- DOM 객체의 이벤트 리스너 프로퍼티에 리스너 함수를 등록했다.
- 코드에서 <body onload="init()">은 완전히 로드되면(load 이벤트 발생) init()함수를 호출한다.
- init()이 리스너 함수 over()와 out()를 등록한다.
--> 결과
3) 이벤트 리스너 작성3(addEventListener())
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addEventListener()를 이용한 리스너 등록</title>
<script>
let p;
function init() { // 문서가 완전히 로드되었을 때 호출
p = document.getElementById("p");
p.addEventListener("mouseover", over); // 이벤트 리스너 등록
p.addEventListener("mouseout", out); // 이벤트 리스너 등록
}
function over() {
p.style.backgroundColor = "orchid";
}
function out() {
p.style.backgroundColor = "white";
}
</script>
</head>
<body onload="init()">
<h3>addEventListener()를 이용한 리스너 등록</h3>
<hr>
<p id="p">마우스 올리면 orchid 색으로 변경</p>
</body>
</html>
- addEventListener()를 사용해 함수 over()를 객체 p의 onmouseover 리스너로 등록하는 코드이다.
--> 결과
4) 이벤트 리스너 작성4(익명 함수)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>익명 함수로 이벤트 리스너 작성</title>
<script>
let p;
function init() { // 문서가 완전히 로드되었을 때 호출
p = document.getElementById("p");
p.onmouseover = function () { // 익명 함수
this.style.backgroundColor = "orchid";
};
p.addEventListener("mouseout",
function () { this.style.backgroundColor = "white"; } // 익명 함수
);
}
</script>
</head>
<body onload="init()">
<h3>익명 함수로 이벤트 리스너 작성</h3>
<hr>
<p id="p">마우스 올리면 orchid 색으로 변경</p>
</body>
</html>
- 익명함수: 함수의 이름 없이 필요한 곳에 함수의 코드를 바로 작성하는 방법이다.
- 위의 코드는 앞의 p 객체의 onmouseover에 등록한 리스너 코드를 익명함수로 만들었다.
--> 결과
5) 이벤트 객체
- 이벤트 객체: 브라우저에 발생한 이벤트에 관련된 다양한 정보를 담는다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 객체 전달받기</title>
</head>
<body>
<p id="p">마우스를 올려 보세요</p>
<button onclick="f(event)">클릭하세요</button><!--event를 넣어 event 객체를 넘긴다.-->
<script>
function f(e) { // e는 현재 발생한 이벤트 객체
alert(e.type); // 이벤트 종류 출력
}
//document.getElementById("p").onmouseover = f;
document.querySelector("#p").addEventListener("mouseover",f);
</script>
</body>
</html>
- 이벤트 객체를 전달받아 이벤트 타입을 출력하는 코드이다.
- 함수 f()를 <button>의 onclick리스너로, <p>의 onmouseover리스너로 중복등록했다.
--> 결과
6) 이벤트 타겟과 target 프로퍼티
- 이벤트 타겟: 이벤트를 우발시킨 객체(태그)이다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 객체 프로퍼티</title>
</head>
<body>
<h3>이벤트 객체의 프로퍼티 출력</h3>
<hr>
<p id="p">버튼을 클릭하면 이벤트 객체를 출력합니다.</p>
<button onclick="f(event)">클릭하세요</button>
<a href="http://www.naver.com" onclick="event.preventDefault()">네이버</a>
<script>
function f(e) { // e는 현재 발생한 이벤트 객체
let text = "type: " + e.type + "<br>"
+ "target: " + e.target + "<br>"
+ "currentTarget: " + e.currentTarget + "<br>"
+ "defaultPrevented: " + e.defaultPrevented;
let p = document.querySelector("p");
p.innerHTML = text; // 이벤트 객체의 프로퍼티 출력
}
</script>
</body>
</html>
- 이벤트 객체의 프로파티를 알아보기 위해 <button>태그를 클릭해 click 이벤트를 발생시키고 click 이벤트 객체의 프로퍼티를 출력했다.
- preventDefault를 이벤트의 디폴트 행동 취소로 네이버 사이트로 이동하지 못한다.
--> 결과
7) preventDefault(), 이벤트의 디폴트 행동 취소
- html 태그 중 몇몇은 특정 이벤트에 대해 디폴트 행동을 한다.(ex) a태그로 url 페이지 이동).
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트의 디폴트 행동 취소</title>
<script>
function query() {
let ret = confirm("네이버로 이동하시겠습니까?");
return ret; // confirm()의 리턴 값은 true 또는 false
}
function noAction(e) {
e.preventDefault(); // 이벤트의 디폴트 행동 강제취소
}
</script>
</head>
<body>
<h3>이벤트의 디폴트 행동 취소</h3>
<hr>
<a href="http://www.naver.com" onclick="return query()">
네이버로 이동할 지 물어보는 링크</a>
<hr>
<form>
<input type="checkbox">빵(체크 됨)<br>
<input type="checkbox" onclick="noAction(event)">술(체크 안됨)
</form>
</body>
</html>
- <a>태그와 <input type="checkbox">태그를 클릭시, 디폴트 행동을 취소하는 코드이다.
- <a>의 경우 링크를 클릭시 confirm()창을 열어 사용자로부터 네이버로 이동할지 묻고 사용자가 취소를 누르면 false를 리턴해 네이버로 이동하지 못한다.
- <input type="checkbox"> 태그의 경우 이벤트 객체의 preventDefault()를 호출해 체그가 일어나지 않게 하였다.
--> 결과
8) 이벤트 흐름
- 이벤트 흐름: 발생한 이벤트는 window객체로부터 DOM트리를 타고 중간 DOM 객체들을 거쳐 타겟 객체로 흘러가고, 다시 반대방향으로 이동해 window객체에 도달 후 없어진다.
1) 캡처 단계: window에서 타겟객체까지 이벤트 객체가 전파되는 과정이다. window와 중간에 있는 모든 DOM 객체들을 거쳐 타겟 객체에 이벤트 객체가 전달된다.
2) 버블단계: 다시 타겟 객체에서 거꾸로 window까지 이벤트 객체가 전파되는 과정이 진행된다. 버블단계에서 실행되도록 작성된 이벤트 리스너가 있다면 순서대로 실행된다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 흐름</title>
</head>
<body>
<p style="color:blue">이것은
<span style="color:red" id="span">문장입니다.
</span>
</p>
<form>
<input type="text" name="s">
<input type="button" value="테스트" id="button">
<hr>
</form>
<div id="div" style="color:green"></div>
<script>
let div = document.getElementById("div"); // 이벤트 메시지 출력 공간
let button = document.getElementById("button");
// body 객체에 캡쳐 리스너 등록
document.body.addEventListener("click", capture, true); // 켭쳐 단계(1)
// 타겟 객체에 버블 리스너 등록
button.addEventListener("click", bubble, false); // 버블 단계(2)
// body 객체에 버블 리스너 등록
document.body.addEventListener("click", bubble, false); // 버블 단계(3)
function capture(e) { // e는 이벤트 객체
let obj = e.currentTarget; // 현재 이벤트를 받은 DOM 객체
let tagName = obj.tagName; // 태그 이름
div.innerHTML += "<br>capture 단계 : " + tagName + " 태그 " + e.type + "이벤트";
}
function bubble(e) { // e는 이벤트 객체
let obj = e.currentTarget; // 현재 이벤트를 받은 DOM 객체
let tagName = obj.tagName; // 태그 이름
div.innerHTML += "<br>bubble 단계 : " + tagName + " 태그 " + e.type + "이벤트";
}
</script>
</body>
</html>
- capture()와 bubble()함수를 작성하고 <input type="button">에는 bubble()을 click이벤트의 버블 리스너를 달고, <body>에는 capture()와 bubble()함수를 각각 캡쳐 리스너와 버블 리스너에 달았다.
- 버튼을 클릭시 <body>에 등록한 capture()함수가 먼저 실행된다.
- 그리고 버블 단계에서 <input type="button">에 등록한 bubble() 함수가 실행된다.
- 그리고 나서 <body>에 등록된 bubble()함수가 실행된다.
--> 결과
'비트교육센터 > 웹' 카테고리의 다른 글
[비트교육센터] 웹 28일차 Javascript, 마우스 핸들링, 윈도우와 브라우저 객체 (0) | 2023.07.07 |
---|---|
[비트교육센터] 웹 26일차 CSS (0) | 2023.07.05 |
[비트교육센터] 웹 25일차 VSCODE 설치, html 기초, html 구조 (0) | 2023.07.04 |