니꼴라 쌤과 함께하는 바닐라 JS로 크롬 앱 만들기를 시작했다!!
이 과정을 통해 바닐라 JS와 좀 더 친해지는 기회가 되길 바라며!!
Start!!
https://nomadcoders.co/javascript-for-beginners
1.3 Sofeware Requirements
크로미움 기반의 브라우저
크로미움 기반의 브라우저는 광고를 막아주며 제일 최신의 브라우저를 사용하고 있는 것
여기서 니꼴라쌤이 말하는 크로미움 기반의 브라우저를 처음 들어서 추가로 구글링을 해보았다!!
크로미움이란?
크로미움이라는 오픈소스 프로젝트에서 만든 브라우저 이름이 크로미움이다. 구글에서 2008년 9월 시작한 프로젝트인 크로미움은 오픈소스 프로젝트 이기 때문에 구글 직원이 아닌 사람들도 참가할 수 있다. 프로젝트의 산물로 나온 크로미움의 소스 코드는 다양한 브라우저들의 기반 엔진이 된다.
크로미움 기반인 브라우저들은 대표적으로 크롬, 엣지, 오페라, 네이버웨일 등이 있다.
** 크로미움 프로젝트 설계 목적 자체가 Google 크롬 브라우저, Chrome OS를 위한 오픈 소스 프로젝트 이었다.
2.2 변수
//변수
console.log(5+2);
console.log(5*2);
//만약 콘솔 안에 있는 숫자를 변겨하고 싶을 때 숫자를 하나하나 바꿔줘여한다.
//극단적으로 저것이 100개라면 우리는 100개 모두 바꿔줘야 하는 상황 발생
//이에 대한 해결책이 바로 변수!!
const a = 5;
const b = 2;
console.log(a+b);
console.log(a/b);
2.3 변수의 종류
1) const
- const 는 바뀌지 않는 값을 의미
- const는 변수 값을 업데이트 할 수 없다.
2) let
- 변수 값을 업데이트 할 수 있다.
⭐const 와 let만을 보고도 코드를 작성한 자의 의도를 파악할 수 있다는 말씀 ⭐
"let을 보고 이 값을 어디선가 업데이트 될 수 있겠군"
업데이트가 되지 않을 경우에는 const를 사용하고 업데이트 하고 싶은 변수라면 let을 사용! 하지만 보통 변수 업데이트 할 일이 많지 않기 때문에 const를 기본적으로 쓰고 때에 맞춰서 let을 사용!
2.4 boolean - true or false
⭐ null하고 false는 다르다!
null은 값이 없는 것 but false는 false라는 값이 존재하는 것!
⭐ null하고 undefined는 ?
const amIFat = null;
let something;
console.log(amIFat); //null 출력
console.log(something); //undefined 출력
let something은 컴퓨터 메모리 안에는 존재하지만(공간은 있지만) 값이 들어가지 않은 것. null은 공간 안에 "비어있음"을 넣은 것 - 자연적으로 값을 넣지 않으면 생기는 undefined와는 달리 직접 null이라는 값을 넣어주여야 생기는 것!!
2.5 배열
const dayOfWeek =["mon","tue","wed","thu"];
console.log(dayOfWeek[0]); //mon 출력
dayOfWeek.push("fri") //dayOfWeek 배열에 4번째 인덱스 값으로 fri가 추가된다
2.6 객체
//배열과는 다른 관련된 묶음이 필요할 때 우리는 객체를 사용한다
const player = {
name:"hia",
points: 100,
cute: true,
};
console.log(player); //객체 전체 출력
console.log(player.cute); //객체 안에 있는 프로퍼티를 '.'을 통해 출력할 수 있다
player.points = 20;
console.log(player); //player 포인트 값이 20으로 업데이트 된다.
player.age = 100;
console.log(player); //age 프로퍼티가 추가된 값으로 나옴
- 객체도 배열처럼 관련된 것을 묶어주는 역할을 한다.
- 하지만 객체 안에 있는 것들을 배열에 넣어주면 'hia'가 무엇을 의미하는지, '100'이 무엇을 의미하는지 모를것이다.
- 객체로 묶어주면 각 값들이 무엇을 의미하는지 쉽게 알 수 있다.
⭐ 위에서 의문점이 우리는 player를 변할 수 없는 값인 const 로 정의해주었는데 왜 player.points에서 값이 업데이트 될 수 있는 것일까??
=> const의 에러는 전체를 하나의 값으로서 업데이트 하려고 할 때 발생
여기서 const는 객체이다. 만약 이 객체를 boolean으로 바꾸면 그때는 에러가 발생!!
ex) player = false; -> 에러 발생!!
2.7 함수
//객체 안에서의 함수
const player= {
name:"hia",
sayHello : function(){
console.log("hello!");
},
};
console.log(player.sayHello()); //hello! 출력됨
//갹체 밖에서는
function sayHello(){
console.log("hello!");
}
const claculaor(){
plus: function(){
a+b;
}
minus:fnction(){
a-b;
}
}
calculator.plus(2,3); //5
2.13 - 15 conditionals - 조건문
** prompt라는 자바스크립트 함수를 잘 사용하지 않는다.
css를 적용할 수 없고 어떤 브라우저에서는 prompt를 거절하기도 하기 때문..!
+ 또한 입력된 값은 숫자가 아닌 문자로 들어가게 된다. (사람들은 현재 html, css로 따로 prompt창을 만들어 사용)
⚠️ 숫자를 입력했는데 문자가 나왔을 때 발생할 수 있는 문제점 ⚠️
1) 숫자끼리 비교해야 하는 상황일 때 비교를 하지 못한다.
2) 다른 타입의 데이터를 입력했을 때 잘못 입력함을 알 수 있다.
const age = prompt("How old are you?");
//parseInt는 string type의 값을 number type으로 변환해준다.
console.log(age, parseInt(age));
//첫번째 age의 type은 string
//두번째 age의 type은 number
const age = parseInt(prompt("How old are you?"));
//isNaN(인자) => 인자를 넣어주면 그것이 number인지 아닌지 boolean으로 판별해주는 함수
//true 면 숫자가 아님
//false 면 숫자
//if(isNaN(age) === true){ -> 처음에 먼저 이렇게 작성했는데 굳이 true를 써줄 필요가 없었음
//if는 기본적으로 true일 때 발생하는 코드를 작성 else는 if의 조건이 false일 때 발생하는 코드
//else if는 if의 조건이 false일 때 한 번 더 실행할 코드
if(isNaN(age)){
parseInt(prompt("Please write a number. "How old are you?""));
}
//or은 하나면 true여도 true
true || true === true
false || true === true
true || false === true
false || false === false
//and는 둘 다 true여야만 true
true && true === true
false && true === false
true && false === false
false && false === false
3.0 The Document Object
자바스크립트를 사용하는 이유는 HTML과 상호작용 하기 위해서이다.
HTML의 element들을 JS를 통해 변경하고 읽을 수 있다!
document.title //HTML의 title 값이 반환
document.title = "HI" //HTML title 값이 'HI'로 변경
document.body //HTML의 body항목들을 읽어올 수 있음
//이것 외에도 document객체에는 많은 것들이 존재함!!
- document는 브라우저에 이미 존재하는 object.
- 내가 접근 가능한 HTML을 가리키는 객체.
- 객체 형태로 나오는 것은 HTML코드를 JS 관점에서 보기 때문!
3.2 Searching For Elements
자바스크립트로 정보를 가져올 수 있는 방법은 document객체와, element를 가져오는 함수를 이용하는 것!
그 중 니꼴라쌤 기준에서 element를 가져오는 가장 coool한 함수는
querySelector querySelectorAll
querySelctor은 id, class, tag를 모두 사용할 수 있고 엘리먼트를 css방식으로 검색할 수 있다.
//querySelector는 단 하나의 첫 번째 element를 return해준다.
//만약 동일 클래스명을 가진 h1을 다 가져오고 싶다면 querySelectorAll를 사용해준다.
document.getElementById("title");
document.getElementsByTagName(".h1");
document.getElementsByClassNAme("hello");
document.querySelector(".hello h1");
document.querySelectorAll(".hello h1");
querySelector 혹은 querySelectorAll이 아닌 다른 함수로는 하위 element를 가져올 수 없음!
3.3 Events
- 우리가 JS에서 대부분 작업할 일은 event를 listen하는 것!
- eventListener는 말 그대로 event를 듣는 것임!
- 여기서 어떠한 이벤트를 들을 것이고 듣고나서 무엇을 실행시킬지 작성해주어야 한다!
const title = document.querySelector("div.hello:first-child h1");
//굳이 버튼이 아니어도 클릭이벤트가 실행된다
function handleTitleClick(){
console.log("title was clicked!");
}
title.addEventListner("click" , handleTitleClick);
//여기서 handleTitleClick() <- 이 괄호가 들어가지 않는 다는 것을 알자!
3.4 Events -2
- 다양한 이벤트가 존재한다!! -> 모질라에서 확인 가능
- on이 붙어 있으면 이벤트이다!
const title = document,querySelector("div.hello:first-child h1");
//굳이 버튼이 아니어도 클릭이벤트가 실행된다
function handleTitleClick(){
console.log("title was clicked!");
}
function handleMouseEnter(){
title.innerText = "Mouse is here"
}
function handleMouseLeave(){
title.innerText = "Mouse is gone"
}
title.addEventListener("click" , handleTitleClick);
//여기서 handleTitleClick() <- 이 괄호가 들어가지 않는 다는 것을 알자!
title.addEventListener("mouseenter",hamdleMouseEnter);
title.addEventListener("mouseleave",hamdleMouseLeave);
3.5 More Events
window차원에서 발생할 수 있는 이벤트
function handleWindowResize(){
document.body.style.backgroundColor="tomato";
}
function handleWindowCopy(){
alert("copier!");
}
window.addEventlistener("resize", handleWindowResize);
window.addEventlistener("copy", handleWindowCopy);
document.head / document.title / document.body 는 가능
document.div 혹은 document.h1 이렇게 가져올 수 없음
document.title은 html의 큰 title을 의미하는 것
만약 title이라는 class이름을 가진 element를 가져오기 위해서는 querySelector등 함수를 써야함!!
3.6 CSS in JS
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
const currentColor = h1.style.color;
let newColor;
if(currentColor === "blue"){
newColor = "tomato";
}else{
newColor = "blue";
}
h1.style.color = newColor;
}
h1.addEventListener("click", handleTitleClick);
- 이렇게 JS를 통해서 CSS를 변경할 수 있다.
- 하지만 JS에서 CSS를 변경하는 것은 좋지 않다! - 언어끼리 섞이기 때문에!
3.7 ~ 3.8 CSS in JS - part 2-3
우리는 자바스크립트로 모든 class name을 변경하지 말아야한다.
h1{
color:cornflowerblue;
transition: color 0.5s ease-in-out;
}
.clicked {
color: tomato;
}
.sexy-font{
font-family: -apple-system, BlinkMacSystemFont,"Segoe UI"
}
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
const clickedClass = "clicked"
if(h1.className === clickedClass){
h1.className="";
}else{
h1.className = clickedClass;
}
}
h1.addEventListerner("clicked", handleTitleClick);
이렇게 했을 때 우리는 한가지 버그를 마주친다. 바로 h1을 클릭했을 때 처음에 적용되었던 sexy-font클래스가 사라지고 handleTitleClick이베트가 실행이 되는 것이다!
이때 해결할 수 있는 방법 =>
classList
classList는 이전 class와 상관하지 않고 모든걸 교체해버리는 classNameclass과 달리 목록으로 작업할 수 있게 허용해준다.
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
const clickedClass = "clicked"
if(h1.classList.contains(clickedClass)){
h1.classList.remove(clickedClass);
}else{
h1.classList.add(clickedClass);
}
}
h1.addEventListerner("clicked", handleTitleClick);
이렇게하면 정상적으로 작동한다!!
하지만 이 코드는 많이 작성하고 자바스크립트는 위 5줄의 코드를 한줄로 만들어버리는
toggle ✨
이있다!!!!!!
toggle은 h1의 classList에 clicked class가 이미 있는지를 확인, 만약 있다면 toggle이 clicked class를 제거해줌
없다면 clicked class를 classList에 추가해준다
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
h1.classList.toggle("clicked");
}
h1.addEventListerner("clicked", handleTitleClick);
5.0 clock - interval
interval은 매번 일어나야 하는 무언가를 말한다. ex) 매 2초, 매 1분
const clock = document.querySelector("h2#clock");
function sayHello(){
console.log("hello");
}
setInterval(sayHello,5000);
//5초마다 sayHello함수가 실행된다.
5.1 Timeouts and Dates
#Timeout
const clock = document.querySelector("h2#clock");
function sayHello(){
console.log("hello");
}
setTimeout(sayHello,5000);
//바로 실행하는 것이 아닌 일정 시간이 지난 뒤에 실행되게
#Date
const clock = document.querySelector("h2#clock");
function getClock(){
const date= new Date();
clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}
getClock();
//getClock함수를 여기서 실행해주지 않으면 1초가 지난 뒤에 시간이 보여진다.
setInterval(getClock,1000);
//1초 마다 시간이 나타남
!! 하지만 !!
두자리 단위가 아닐 경우 한자리로만 나타나게 된다. 우리는 19:20:7 이 아닌 19:20:07로 바꾸고 싶다!!!
=> 이에 대한 해결책이 바로
PadStart
(공부하면서 느끼지만 자바스크립트에는 웬만한 기능이 있는 것 같다..ㅎㅎ)
5.2 PadStart
const clock = document.querySelector("h2#clock");
function getClock(){
const date= new Date();
const hours = String(date.getHours()).padStart(2,"0");
const minutes = String(date.getMinutes()).padStart(2,"0");
const seconds = String(date.getSeconds()).padStart(2,"0");
clock.innerText = `${hours}:${minutes}:${seconds}`;
}
getClock();
setInterval(getClock,1000);
붐!! 원하는대로 19:31:1이 아닌 19:31:01로 나오게 되었다!
6.0 Quotes
const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
6.1 BackGround
const images = ["0.jpeg", "1.jpeg", "2.jpeg"];
//이미지 수 만큼 랜덤
const chosenImage = images[Math.floor(Math.random() * images.length)];
const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImage}`;
document.body.appendChild(bgImage);
'Frontend' 카테고리의 다른 글
url 상태관리 (0) | 2024.07.15 |
---|---|
moduleResolution이란 (0) | 2024.06.08 |
Button 태그에 type을 명시하면 좋은 점 (0) | 2023.07.25 |
브라우저 렌더링 엔진 동작과정 + 웹페이지 속도 최적화 (0) | 2023.03.13 |
< Flex 정리 > (0) | 2022.03.10 |