Nomad Coders "바닐라 JS로 크롬 앱 만들기"
- JavaScript for Beginners
GDSC FE-Toy Project Study Plan
• 되도록이면 기능 단위 commit (branch 생성)
• 제작 시 커스텀, 수정, 추가 자유롭게 해보기
• 전 과정, 시행착오 기록하기
• PR 미리 날려서 commits 기록 및 간단한 수정 계획 comments로 남기기
Week 1) ~10/7
• 강의 #3.5까지 수강 (개념 & 예제)
• 강의 내용, 추가 공부 내용 정리
Week 2) ~10/14
• 강의
JavaScript Basics
• 브라우저는 html 파일을 열고, html은 css와 javascript를 가져온다. (html = glue)
• variables 선언
1) const
- 한 번 선언한 후 값을 변경할 수 없다. (constant)
- variable을 절대 바뀌지 않도록 설정하고 싶을 때가 존재
2) let
- 선언한 후에 값을 변경할 수 있다.
Ex) let myName = "Joong";
myName = "Kim"; //myName값을 Kim으로 변경
3) var
- 과거에는 var만 존재
-실수로 값들을 바꿔도 알 수가 없으니, const로 값을 바꿀 수 없도록 보호하도록 업데이트
→ 기본적으로 const를 사용하고, 필요할 때만 let을 쓰되, var는 사용하지 않는다.
• Data Type
1) Boolean
- True / False
- 활용 예시) 사용자의 로그인 여부 확인, 비디오의 재생 여부, 웹사이트 로딩 여부 등 true/false로 답할만한 것들
2) null
- 아무것도 없음을 의미
- 절대 자연적으로 발생하지 않는다
- js에게 값이 없다는 것을 알리기 위해 사용
3) undefined
- 아직 define되지 않은 것
- 메모리 공간은 존재하는데(variable을 선언하긴 했기 때문), 그 값을 아직 정의하지 않아 값이 없는 상태
• Array
- 대괄호
Ex) const daysOfWeek = ["mon", "tue", "wed", "thu", "fri", "sat"];
array 내부의 데이터에 접근 시 → daysOfWeek[2];
array 생성 후 데이터 추가 시 → daysOfWeek.push("sun");
• Objects
const playerName = "Nico";
const playerPoints = "1234";
const playerHandsome = "false";
const playerFat = "little bit";
예시에서 name, points, handsome, fat과 같은 property가 하나의 entity(player)를 가리키므로,
위와 같이 쓸 필요가 없다.
const player = {
name: Nico,
points: 10,
fat: true;
}
- 중괄호
- object 내부에 접근하는 두 가지 방법
1) player.name
2) player["name"]
- object 업데이트하기
Ex) player.fat = false; //player object의 fat값이 true에서 false로 업데이트
- object에 추가하기
Ex) player.lastName = "potato";
→ array의 element들은 모두 같은 의미를 가진다.
예를 들어, daysOfWeek[]의 element들은 모두 요일을 나타낸다.
반면, objects는 한 entity에 대해서 다양한 property를 모아둔 것이다.
• Function
function plus(a, b) {
console.log(a + b);
}
plus(8, 60);
- 함수 외부에서 함수로 데이터 전달
const player = {
name: Nico,
sayHello: function() {
console.log("hello!");
},
};
player.sayHello();
- 객체 내부에 함수 작성
JavaScript on the Browser
• JavaScript에서 HTML의 항목들을 읽어올 수 있고, 반대로 항목들을 추가할 수도 있다.
→ documents.title: documents에서 title값을 읽어오기
documents.body: documents에서 body 내용을 불러오기
• Elements 찾기
js 파일에서 html의 elements search
→ html 파일에서 해당 js 파일을 import했기 때문에 가능
1) document.querySelector 이용
- CSS 방식으로 element 검색
- 단 하나의 element return
2) document.getElementById
- 주어진 문자열과 일치하는 id를 가진 element를 찾아 return
- id는 유일한 property이므로 항상 하나의 element를 return
✏️ document.querySelector(selectors);
• Document object의 method 중 하나
• 선택자(또는 선택자 뭉치)와 일치하는 문서 내 첫 번째 element를 반환/일치하는 element가 없으면 null 반환
• 선택자는 CSS 선택자
→ id: #example
class: .example• 선택자를 만족하는 모든 요소의 목록이 필요할 시, querySelectorAll() 사용
CSS Selectors Reference)
https://www.w3schools.com/cssref/css_selectors.asp
CSS Selectors Reference
CSS Selector Reference CSS Selectors In CSS, selectors are patterns used to select the element(s) you want to style. Use our CSS Selector Tester to demonstrate the different selectors. Selector Example Example description .class .intro Selects all elements
www.w3schools.com
querySelector Manual)
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
Document.querySelector() - Web APIs | MDN
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
developer.mozilla.org
✏️ document.getElementById(id);
•document 객체의 method로만 사용 가능
•매개변수 id값 대소문자 구분
Ex) name과 Name은 다른 값•id와 일치하는 element를 찾을 수 없을 때 null return
getElementById Manual)
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Document.getElementById() - Web APIs | MDN
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quick
developer.mozilla.org
• Events
- javascript는 event를 listen할 수 있다.
Ex) 마우스를 h1 위에 둔다 (hover)
마우스 클릭
입력을 끝낸다
enter를 누른다
💻 Example Code
const h1 = document.querySelector('.hello h1');
function handleTitleClick() {
h1.style.color = 'blue';
}
function handleMouseEnter() {
h1.innerText = 'Mouse is here!';
}
function handleMouseLeave() {
h1.innerText = 'Mouse is gone!';
}
function handleWindowResize() {
document.body.style.backgroundColor = 'gray';
}
function handleWindowCopy() {
alert('copier!');
}
function handleWindowOffline() {
alert('SOS NO WIFI!');
}
function handleWindowOnline() {
alert('ALL GOOOD!');
}
h1.addEventListener('click', handleTitleClick);
h1.addEventListener('mouseenter', handleMouseEnter);
h1.addEventListener('mouseleave', handleMouseLeave);
window.addEventListener('resize', handleWindowResize);
window.addEventListener('copy', handleWindowCopy);
window.addEventListener('offline', handleWindowOffline);
window.addEventListener('online', handleWindowOnline);
<Event를 사용하는 2가지 방법>
1) eventListener를 이용해 listen (event를 특정해주는 것이 필요)
- addEventListener()
Ex) title.addEventListener("click", handleTitleClick);
→ function을 js에게 넘겨주고, 지정한 event가 발생했을 때 function을 실행하도록
→ listen할 event, event 발생 시 호출할 function
2) oneventname property에 event listener를 할당
Ex) title.onclick = handleTitleClick;
✏️ target.addEventListener(type, listener[, options]);
Ex) title.addEventListener("click", handleTitleClick);
→ title을 target으로, click event 발생 시 handleTitleClick 함수 호출
• Parameters
1) type
listen할 event 유형 (대소문자 구분, 문자열)
2) listener
event 발생 시 알림을 받는 객체 (js function을 구현하는 객체)
3) options
https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback
EventTarget.addEventListener() - Web API | MDN
EventTarget의 addEventListener() 메서드는 지정한 이벤트가 대상에 전달될 때마다 호출할 함수를 설정합니다.
developer.mozilla.org
• CSS in Javascript
위의 code example에서 handleTitleClick()에만 집중해서 수정해보자.
💻 Example Code
const h1 = document.querySelector('.hello h1');
function handleTitleClick() {
if (h1.style.color === 'green') {
h1.style.color = 'tomato';
} else {
h1.style.color = 'green';
}
}
h1.addEventListener('click', handleTitleClick);
1. addEventListener로 h1이 클릭되는지 확인
2. h1이 클릭되면 handleTitleClick() 수행
→ handleTitleClick(): h1의 color가 green이면 tomato로 바꾸고,
green이 아니면(black(초기상태) or tomato면) green으로 바꿔라
const h1 = document.querySelector('.hello h1');
function handleTitleClick() {
const currentColor = h1.style.color;
let newColor;
if (currentColor === 'green') {
newColor = 'tomato';
} else {
newColor = 'green';
}
h1.style.color = newColor;
}
h1.addEventListener('click', handleTitleClick);
위의 example code를 modify해보자
→ const와 let을 이용해 현재 색을 나타내는 currentColor와 변경된 색인 newColor를 선언하자
이 메소드가 지금 어떤 일을 하는지 한 눈에 알아보기 쉽게 표현할 수 있다!
Step 1) Element를 찾아라
const h1 = document.querySelector('.hello h1');
Step 2) Event를 listen해라
h1.addEventListener('click', handleTitleClick);
Step 3) 그 Event에 react해라
function handleTitleClick() {
const currentColor = h1.style.color;
let newColor;
if (currentColor === 'green') {
newColor = 'tomato';
} else {
newColor = 'green';
}
h1.style.color = newColor;
}
💻 Example Code
function handleTitleClick() {
const clickedClass = 'clicked';
if (h1.classList.contains(clickedClass)) {
h1.classList.remove(clickedClass);
} else {
h1.classList.add(clickedClass);
}
}
- h1의 classList가 clickedClass를 포함하고 있는지 확인 후, 있으면 classList에 remove, 없으면 add
→ toggle()로 간단히 구현 가능
function handleTitleClick() {
h1.classList.toggle('clicked');
}
- toggle(): h1의 classList에 clicked class가 있는지 확인해서 있다면 clicked를 remove,
없으면 h1의 classList에 clicked class를 add
출처
https://nomadcoders.co/javascript-for-beginners
바닐라 JS로 크롬 앱 만들기 – 노마드 코더 Nomad Coders
Javascript for Beginners
nomadcoders.co