아주 기초적인 JS, 자주 쓰이는 것들, 생각이 번뜩 안날 때 검색해서 찾아보자
Input 입력 검증 required
<form action="서버측 페이지.php" method="post">
자동차 회사 이름: <input type="text" name="makerName" required>
<input type="submit" value="입력하기">
</form>
HTML 입력 속성 검증
required 이 속성은 불리언 속성인데 true 가 되려면 제출되기 전에 입력 필드가 채워져야 합니다.
type 입력 태그의 형식을 지정합니다.
max 입력 태그의 최대값을 지정합니다.
min 입력 태그의 최소값을 지정합니다.
CSS 선택자 검증
:required input:required 처럼 사용하여, 모든 required 속성을 갖는 <input> 태그를 선택합니다.
:disabled input:disabled 처럼 사용하여, 모든 disabled 속성을 갖는 <input> 태그를 선택합니다.
:valid input:valid 처럼 사용하여, 모든 valid 값을 갖는 <input> 태그를 선택합니다.
DOM 속성 검증
validity 입력 태그의 유효성 여부를 true 또는 false 의 불리언 속성으로 갖습니다.
validationMessage 위의 validity 가 false 일 때, 브라우저가 표시할 메시지 값을 갖습니다.
예시1
<p>입력 필드에 5 에서 8 이내의 값을 입력하세요.</p>
<input id="myInputValue2" type="number" min="5" max="8">
<button onclick="myCheckValidityFunction2()">입 력</button>
<p>사용자가 입력한 값이 5 에서 8 사이를 벗어나면 에러 메시지를 띄울 것입니다.</p>
<p id="myCheckValidityResult2"></p>
<script>
function myCheckValidityFunction2() {
var myData2 = "";
if (document.getElementById("myInputValue2").validity.rangeUnderflow) {
myData2 = "값이 너무 작습니다.";
} else if (document.getElementById("myInputValue2").validity.rangeOverflow) {
myData2 = "값이 너무 큽니다.";
} else {
myData2 = "입력 되었습니다.";
}
document.getElementById("myCheckValidityResult2").innerHTML = myData2;
}
</script>
예시2
<p>입력 필드에 5 에서 8 이내의 값을 입력하세요.</p>
<input id="myInputValue" type="number" min="5" max="8">
<button onclick="myCheckValidityFunction()">입 력</button>
<p>사용자가 입력한 값이 5 에서 8 사이를 벗어나면 에러 메시지를 띄울 것입니다.</p>
<p id="myCheckValidityResult"></p>
<script>
function myCheckValidityFunction() {
var myData = document.getElementById("myInputValue");
if (myData.checkValidity() == false) {
document.getElementById("myCheckValidityResult").innerHTML = myData.validationMessage;
} else {
document.getElementById("myCheckValidityResult").innerHTML = "정상적으로 입력 되었습니다.";
}
}
</script>
자바스크립트 객체
객체 (Objects) 는 모두 객체 입니다.
배열 (Arrays) 은 항상 객체 입니다.
함수 (Functions) 도 항상 객체 입니다.
날짜 (Dates) 도 항상 객체 입니다.
수학 처리를 하는 Maths 도 항상 객체 입니다.
정규 식 (Regular expressions) 은 항상 객체 입니다.
불리언 (Booleans) 은 객체일 수도 있고, 아니면 객체 처럼 취급되는 원시 데이터 일 수 있습니다.
숫자 (Numbers) 도 객체일 수도 있고, 아니면 객체 처럼 취급되는 원시 데이터 일 수 있습니다.
문자열 (Strings) 도 또한 객체일 수도 있고, 아니면 객체 처럼 취급되는 원시 데이터 일 수 있습니다.
자바스크립트 객체는 named values의 집합, 이 named values는 property 라고 부름
property:"value"
객체는 값을 직접 가리키는 것이 아니라 참조할 주소를 가리킴. 할당하면 값을 복제하는 것이 아니라 주소
를 복제함
자바스크립트의 객체의 프로퍼티에 접근하는 구문 (syntax)
객체이름.프로퍼티 // car.maker
객체이름["프로퍼티"] // car["modelName"]
객체이름[식] // cc = "2700"; car[cc]
for (매개변수 in 객체) {
실행될 코드들;
}
<p id="forInResult"></p>
<script>
var personHistory = "";
var seJong = {name:"세종", job:"임금", birthPlace:"한성 준수방", year:1397, brother:"이제"};
var temp;
for (temp in seJong) {
personHistory += seJong[temp] + " ";
}
document.getElementById("forInResult").innerHTML = personHistory;
</script>
객체 프로퍼티 추가
seJong.hisFather = "이방원";
객체 프로퍼티 삭제
delete seJong3.year;
객체 메서드
프로퍼티 값
job 장군
birthPlace 한성 마르내골
year 1545
friend 유성룡
birthInfo function() {return this.year + "년에 " + this.birthPlace + "에서 태어나셨습니다.";}
객체이름.메서드이름()
함수 function
function 함수이름(매개변수) {
실행할 코드들;
}
//함수명 사용
function myCircumferenceFunction(a) {
var c = a * 3.14159;
return "직경이 " + a + "이면, 원둘레는 " + c;
}
//변수처럼 사용
var myfunctionVariable = function (a) {
var c = a * 3.14159;
return "직경이 " + a + "이면, 원둘레는 " + c;
};
함수 스스로 호출하기, 바로 실행
(function () {})();
함수이름(매개변수_1, 매개변수_2) {
실행될 코드들;
}
함수 매개변수 (parameter) 들은 함수의 정의에 나열된 이름 들
입니다.
함수 인자 (argument) 들은 함수가 받는 또 함수에 건네진 진짜
값들 입니다.
arguments 라는 내장 객체를 이용해 인수중 가장 작은 값 찾기
function findMin() {
var i;
var min = Infinity;
for(i = 0; i < arguments.length; i++) {
if (arguments[i] < min) {
min = arguments[i];
}
}
return min;
}
객체 생성하여 프로퍼티와 메서드 가지도록 함수 정의 this 키워
드 사용 호출
<script>
var invokingMethodObject = {
hisName:"세종",
hisJob: "임금",
hisRealName:"이도",
jobAndName: function() {
return this.hisName + " " + this.hisJob + " 의 이름은 " +
this.hisRealName + " 였습니다. ";
}
}
document.getElementById("invokingMethodResult").innerHTML
= invokingMethodObject.jobAndName();
</script>
apply(), call()
<script>
var myfunctionMethodObject;
function myfunctionMethod(a, b) {
return a * b;
}
myfunctionMethodObject = myfunctionMethod.call
(myfunctionMethodObject, 1000, 3.14159);
document.getElementById("functionMethodResult").innerHTML
= myfunctionMethodObject;
</script>
apply와 call은 1번째 매개변수로 소유주 객체를 지정함
전역변수, 지역변수 Variable Lifetime
DOM(Document Object Model 문서 객체 모델)
Core DOM, XML DOM, HTML DOM 중
HTML DOM은 아래를 정의하고 있음
객체로서의 HTML 태그
모든 HTML 태그의 프로퍼티 (properties)
모든 HTML 태그에 접근하기 위한 메서드
모든 HTML 태그에 대한 이벤트
document.getElementById("innerHTMLResult").innerHTML = "여
기가 추가된 값입니다.";
getElementById는 메서드 .innerHTML은 프로퍼티
document.getElementById(id) - 태그의 id 로 특정 태그를 찾습니
다.
document.getElementsByTagName(name) - 태그의 이름
으로 특정 태그를 찾습니다.
document.getElementsByClassName(name) - 클래스 이름
으로 특정 태그를 찾습니다.
element.innerHTML = 새로운 HTML 내용 - 태그의 내부
HTML 내용을 바꿉니다.
element.attribute = 새로운 값 - HTML 태그의 속성 값 (attribute
value) 을 바꿉니다.
element.setAttribute(attribute, value) - HTML 태그의 속성 값
(attribute value) 을 바꿉니다.
element.style.property = 새로운 스타일 - HTML 태그의 스타일
을 바꿉니다.
document.createElement(element) Create an HTML
element
document.removeChild(element) Remove an HTML
element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML
element
document.write(text) Write into the HTML output
stream
document.getElementById(id).onclick = function(){실행할 코드들
} - onclick event 에 이벤트 핸들러
HTML DOM 태그 접근
id, tag, class, css selector, object collections
---id---
var myFirstParagraphContent = document.getElementById
("firstParagraph");
---tag---
var pBelowDiv = document.getElementById
("firstDIV").getElementsByTagName("p");
---class---
var allMyClass = document.getElementsByClassName
("myClass");
---css selector---
var all_P_SelectorClass = document.querySelectorAll
("p.selectorClass");
all_P_SelectorClass[1].innerHTML
---object collection---
<script>
function myCollectionFunction() {
var allCollections = document.forms["collectionID"];
var result = "";
var i;
for (i = 0; i < allCollections.length ;i++) {
result += allCollections.elements[i].value + ", ";
}
document.getElementById("myCollectionResult").innerHTML =
result;
}
</script>
HTML DOM 태그 변경
document.write()으로 출력
<p>현재의 시각은 : </p>
<script>
document.write(Date("Month dd, yyyy hh:mm:ss"));
</script>
document.getElementById("특정 id").innerHTML = 새로운 HTML
내용
document.getElementById("특정 id").attribute = 새로운 HTML
속성 값
document.getElementById("myImage").src =
"https://cdn2.iconfinder.com/data/icons/new-year-
resolutions/64/resolutions-10-128.png";
HTML DOM 스타일 변경
<p><span id="styleID">안</span>녕하세요.</p>
<script>
document.getElementById("styleID").style.color = "blue";
document.getElementById("styleID").style.fontSize = "300%";
</script>
<p><span id="eventID">안</span>녕하세요.</p>
<button type="button"
onclick='document.getElementById("eventID").style.color =
"blue";
document.getElementById("eventID").style.fontSize = "300%"';
">맨 앞의 한글자를 청색에 3배 크기로 바꾸기</button>
JavaScript Animation
클릭 시 absolute인 태그의 style top position 변경
<style>
#myContainer {
width: 480px;
height: 320px;
position: relative;
background: LightGreen;
}
#myBullet {
width: 10px;
height: 40px;
position: absolute;
left: 240px;
top: 280px;
background-color: Red;
}
</style>
<div id ="myContainer">
<div id ="myBullet"></div>
</div>
<script>
function myAnimationMove() {
var bullet = document.getElementById("myBullet");
var posX = 480 * Math.random();
var posY = 280;
var id = setInterval(myFrame, 1);
function myFrame() {
if (posY == -40) {
clearInterval(id);
} else {
posY--;
bullet.style.top = posY + 'px';
bullet.style.left = posX + 'px';
}
}
}
</script>
<p>
<button onclick="myAnimationMove()">한발씩 총알
발사하기</button>
</p>
JavaScript Event
<button onclick="dateFunction()">버튼을 클릭하면 이벤트가 실
행됩니다.</button>
document.getElementById("eventID").onclick =
eventDisplayDate;
<input type="text" id="onchangeEventID"
onchange="onchangeEventFunction()">
function onchangeEventFunction() {
var onchangeEventValue = document.getElementById
("onchangeEventID");
onchangeEventValue.value =
onchangeEventValue.value.toUpperCase();
}
<div onmouseover="myMouseOver1(this)"
onmouseout="myMouseOut1(this)"
style="background-color:
Chartreuse;width:300px;height:16px;padding:20px;">선을 넘으면
글자가 바뀝니다.</div>
<div onmousedown="myMouseDown1(this)"
onmouseup="myMouseUp1(this)"
style="background-color:
Chartreuse;width:300px;height:16px;padding:20px;">마우스를 누
르거나 뗄 때 글자가 바뀝니다.</div>
JavaScript EventListener
document.getElementById
("myEventListenerButton").addEventListener("click",
myDateFunction);
태그.addEventListener(이벤트 타입, 호출될 함수, useCapture);
이벤트 핸들러는 계속해서 추가됨
이벤트 버블링 event bubbling: 내부태그부터 바깥 태그 순으로
이벤트 발생
이벤트 캡처링 event capturing
useCapture defalut : false - 이벤트 버블링됨, true - 이벤트 캡처
링
이벤트 제거 removeEventListener()
HTML DOM 노드 탐색
parentNode
childNodes[노드번호]
firstChild
lastChild
nextSibling
previousSibling
var hisName = document.getElementById
("greatMan").firstChild.nodeValue;
document.getElementById("theName").innerHTML = hisName;
HTML DOM 노드 추가 삭제
var new_P_Tag = document.createElement("p");
var new_Text_Node = document.createTextNode("새로 추가된
텍스트 노드입니다.");
new_P_Tag.appendChild(new_Text_Node);
var old_Div_Tag = document.getElementById("divID");
old_Div_Tag.appendChild(new_P_Tag);
<div id="insert_divID">
<p id="insert_pID1">기존에 있던 문장 1 입니다.</p>
<p id="insert_pID2">기존에 있던 문장 2 입니다.</p>
</div>
<script>
var new_P_Tag = document.createElement("p");
var new_Text_Node = document.createTextNode("새로 추가된
텍스트 노드입니다.");
new_P_Tag.appendChild(new_Text_Node);
var old_Div_Tag = document.getElementById("insert_divID");
var pID1_Tag = document.getElementById("insert_pID1");
var pID2_Tag = document.getElementById("insert_pID2");
old_Div_Tag.insertBefore(new_P_Tag, pID1_Tag);
old_Div_Tag.removeChild(pID2_Tag);
</script>
old_Div_Tag.replaceChild(new_P_Tag, pID2_Tag);
HTML DOM 노드 리스트
getElementsByTagName()
var nodeList = document.getElementsByTagName("h4");
document.getElementById("nodeListResult").innerHTML =
nodeList.length;
<h4>성명: 이 도</h4>
<h4>직업: 임금</h4>
<h4>묘호: 세종</h4>
<p id="nodeListLoopResult"></p>
<script>
var nodeListLoop = document.getElementsByTagName("h4");
var i;
var totalNodeListLoop = "";
for (i = 0; i < nodeListLoop.length; i++) {
totalNodeListLoop += nodeListLoop[i].innerHTML + ", ";
}
document.getElementById("nodeListLoopResult").innerHTML =
nodeListLoop.length + "개의 문장을 모두 합하면 = " +
totalNodeListLoop;
</script>
JavaScript Window
Browser Object Model, BOM 브라우저 객체
window.innerHeight - 브라우저 창의 픽셀 단위의 내부 높이를 의
미합니다.
window.innerWidth - 브라우저 창의 픽셀 단위의 내부 폭을 의미
합니다.
var myWidth = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var myHeight = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
window.open() - 새 창을 띄웁니다.
window.close() - 현재 창을 닫습니다.
window.moveTo() - 현재 창을 이동 시킵니다.
window.resizeTo() - 현재 창의 크기를 조절합니다.
윈도우 화면 객체 screen window 접두사 없이도 사용
screen.width
screen.height
screen.availWidth
screen.availHeight
screen.colorDepth
screen.pixelDepth
윈도우 window.location 객체
window.location.href - 현재 페이지의 href 주소를 반환
합니다.
window.location.hostname - 웹 서버 (호스트) 의 도메인 이름
을 반환합니다.
window.location.pathname - 현재 페이지의 경로와 파일이름
을 알려줍니다.
window.location.protocol - 사용된 웹 프로토콜이 무엇인지
알려줍니다. (http:// 인지 아니면 보안이 강화된 https:// 인지)
window.location.assign - 새로운 문서를 로딩합니다.
윈도우 히스토리
history.back() - 브라우저에서 백 버튼 클릭과 동일한 기능을 보이
며, 히스토리 목록에서 이전의 URL을 로드 합니다.
history.forward() - 브라우저에서 포워드 버튼 클릭과 동일한 기능
을 보이며, 히스토리 목록에서 다음의 URL을 로드 합니다.
윈도우 네비게이터 window.navigator
navigator.cookieEnabled - 이 프로퍼티가 true 일때는 쿠키
(cookie, 인터넷 웹사이트 방문기록) 가 작동중이라는 것을 나타냅
니다.
navigator.appName - 브라우저의 이름을 나타냅니다.
navigator.appCodeName - 브라우저의 코드이름을 나타냅니
다.
navigator.product - 브라우저 엔진을 알려줍니다.
navigator.appVersion - 브라우저 버전 정보를 나타냅니
다.
navigator.platform - 이 프로퍼티는 브라우저의 운영체제를 보
여줍니다.
navigator.language - 브라우저의 언어설정을 보여줍니다.
navigator.javaEnabled() - 이 메서드는 자바가 가능할 때
True 를 반환합니다.
JavaScript popup box
alert("안녕하세요. 경고 상자는 선택버튼이 하나밖에 없군요.");
confirm()은 버튼 2개
<p>아래 버튼을 클릭하여 확인 상자를 띄웁니다.</p>
<button onclick="myConfirmFunction()">확인 상자
띄우기</button>
<p id="confirmResult"></p>
<script>
function myConfirmFunction() {
var myConfirm;
if (confirm("버튼을 눌러 주시겠어요?") == true) {
myConfirm = "OK 를 누르셨습니다.";
} else {
myConfirm = "Cancel 을 누르셨습니다.";
}
document.getElementById("confirmResult").innerHTML =
myConfirm;
}
</script>
입력대기 상자 promp box
<p>입력 대기 상자 (prompt box) 를 띄우고 값을 입력해
보세요.</p>
<button onclick="myPromptFunction()">입력 대기 상자 띄우기
</button>
<p id="promptResult"></p>
<script>
function myPromptFunction() {
var bestWish = prompt("소원을 말씀해 보세요.\n당신은 무엇이
든 될수가 있습니다.", "최고의 프로그래머 되기");
if (bestWish != null) {
document.getElementById("promptResult").innerHTML =
"당신의 소원은 " + bestWish + "입니다." + "<br />소원을 꼭 이
루시길 바랍니다.";
}
}
</script>
JavaScript 타이밍 이벤트
setTimeout(function, milliseconds) 특정 밀리 세컨즈 (천분
의 1초) 단위로 기다렸다가 함수를 실행합니다.
setInterval(function, milliseconds) setTimeout()과 동일하
지만, 그 함수를 끊임없이 반복 실행합니다.
예시1
<p>팝업 띄우기를 클릭하면 2.5초 만에 팝업이 뜹니다. 그 전에
취소하기를 클릭하면, 팝업은 뜨지 않습니다.</p>
<button onclick="mySetTimeoutVar = setTimeout
(mySetTimeoutFunction, 2500)">팝업 띄우기</button>
<button onclick="clearTimeout
(mySetTimeoutVar)">취소하기</button>
<script>
function mySetTimeoutFunction() {
alert("2.5초 내에 취소되지 않아 팝업이 뜬 것입니다.");
}
</script>
예시2
<p>이 페이지의 스크립트에 의해 디지털 시계가 1초마다 갱신되
고 있습니다.</p>
<p>시계 멈추기 버튼을 클릭하여 중지해 보세요.</p>
<p id="myClockResult"></p>
<button onclick="clearInterval(mySetIntervalVar)">시계
멈추기</button>
<script>
var mySetIntervalVar = setInterval(myDateTimer ,1000);
function myDateTimer() {
var dateVariable = new Date();
document.getElementById("myClockResult").innerHTML =
dateVariable.toLocaleTimeString();
}
</script>
JavaScript Cookie
document.cookie = "yourName = 강감찬; expires = Thu, 31 Dec
2020 00:00:01 UTC";
예제
<script>
function mySetCookieFunction
(cookieName,cookieValue,expiryDate) {
var d = new Date();
d.setTime(d.getTime() + (expiryDate*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookieName+"="+cookieValue+"; "+expires;
}
function myGetCookieFunction(cookieName) {
var name = cookieName + "=";
var allCookies = document.cookie.split(';');
for(var i=0; i < allCookies.length; i++) {
var aCookie = allCookies[i];
while (aCookie.charAt(0)==' ') aCookie = aCookie.substring(1);
if (aCookie.indexOf(name) == 0) {
return aCookie.substring(name.length, aCookie.length);
}
}
return "";
}
function myDeleteCookieFunction() {
document.cookie = "username=; expires=Thu, 01 Jan 1970
00:00:00 UTC";
}
function myCheckCookieFunction() {
var yourName = myGetCookieFunction("username");
if (yourName != "") {
alert(yourName + " 님 다시 방문해 주셔서 고맙습니다.");
} else {
yourName = prompt("놀라지 마세요. 쿠키를 설명하기 위해 팝업
이 떴습니다. 이름을 입력해 주세요.","");
if (yourName != "" && yourName != null) {
mySetCookieFunction("username", yourName, 10);
}
}
}
</script>
<body onload="myCheckCookieFunction()">
<p>1. 이 웹 페이지가 호출될 때, 쿠키를 입력 받습니다.</p>
<p>2. 이때 이름을 넣으면, 쿠키에 저장됩니다.</p>
<p>3. 다시 이 페이지에 들어오거나, 리로드를 하면, 저장된 이름
을 가져와 환영 메시지를 띄웁니다.</p>
<p>* 아래의 쿠키 삭제 버튼을 누르면, 쿠키는 삭제됩니다.</p>
<p>* 삭제된 후 이 페이지를 리로드하면, 다시 쿠키입력 화면이
뜹니다.</p>
<button onclick="myDeleteCookieFunction()">쿠키
삭제하기</button>
</body>
'Development > WEB' 카테고리의 다른 글
블로그 특정 위치로 스크롤링 시키는 간단 자바스크립트 (0) | 2019.10.15 |
---|---|
javascirpt 기초(1/2) (0) | 2017.10.30 |
CSS 기초 (0) | 2017.09.13 |
HTML5 기초 (0) | 2017.09.07 |
MongoDB에서 데이터 가져와서 template 뷰와 바인딩 (0) | 2017.03.06 |