Frontend

바닐라 Js로 크롬 앱 만들기 #2 PRACTICE

단점이없어지고싶은개발자 2021. 5. 19. 02:30
반응형

# 2PRACTICE

 

2.0 Your first JS Function

함수란? 수행하려는 한 부분을 여러번 쓸 수 있다.

 

argument(인자)

 

함수는 인자를 받는다. 인자는 변수다 우리가 주는 값을 저장한다.

 

function sayHello(potato){ //함수안에 인자를 넣으면 외부에 있는 데이터를 줄 수 있다.

console.log("hello!", potato);

}

 

sayHello("Nicolas");

 

---

 

function sayHello(name, age){

console.log("hello!", name, "you have", age, "years of age.");

}

 

sayHello("Nicolas", 15);

console.log();

 

함수 안에 인자를 넣어줄 수 있다.

 

2.1 More Function Fun

'', ""로 string을 감싸줘야한다. 또는 ``백터를 이용해서 전체를 감싸줄 수 있다.

 

function sayHello(name, age){

console.log(`Hello ${name} you are ${age} years old`);

}

 

const calculator = {

plus: function(a, b) {

return a + b;

}

}

const plus = calculator.plus(5, 5);

 

const cal = {

min: function(a, b) {

return a - b;

}

}

const min = const.min(5, 3);

console.log(min);

 

2.2 JS DOM Functions

JS에서 document라는 함수는 HTML을 다루는 걸 허용한다

 

const title = document.getElementById("title");

 

console.log(title);

DOM = Document Object Module

자바스크립트는 HTML 태그를 가져와 모든걸 객체로 바꿔준다.

자바스크립트에서 HTML내용 또한 변경할 수 있다

 

2.3 Modifying the DOM with JS

 

const title = document.getElementById("title");

console.dir(document);

document.title = "i onw you now";

 

위 처럼 HTMl의 내용을 JS에서 수정 가능하다

 

2.4 Events and event handlers

이벤트란 웹사이트에서 발생하는 것들을 다루기 위해 만들어 졌다.

 

function handleResize() {

console.log("I have been reasized");

}

 

window.addEventListener("resize", handleResize()); // ()붙여주면 자동으로 호출하고, 붙여주지 않으면 죽시 호출하지 않는다

 

2.5 if, else, and, or

 

if(condition) {

block true 일 때

} else {

block false 일 때

}

 

2.6 DOM - if else -Function practice

const title = document.querySelector('#title');

 

const BASE_COLOR = "rgb(52, 73, 94)";

const OTHER_COLOR = "#7f8c8d";

 

function handleClick() {

const currentColor = title.style.color;

if(currentColor === BASE_COLOR) {

title.style.color = OTHER_COLOR;

} else {

title.style.color = BASE_COLOR;

}

}

 

function init() {

title.style.color = BASE_COLOR;

title.addEventListener("click", handleClick);

}

 

init();

 

이런식으로 로직을 추가할 수 있다. 이벤트는 많기 때문에 MDN에서 Event reference를 찾으면 된다.

 

2.7 DOM-if else-Function practice Two

반응형