Knowhow/Web

Javascript tips

침닦는수건 2022. 6. 21. 09:05
반응형

1. 기본 골자는 html이 javascript를 실행시켜주는 형태로 다음과 같이 시작함.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
	<script src="app.js"></script>
</body>
</html>

 

2. 연동된 html 코드는 document라는 object로 정의되어 있음.

const title = document.getElementById("title");
const title = document.querySelector(".hello h1"); // css style indexing
console.dir(title);

 

3. event 는 2가지 형태로 구현이 가능함. 개인적으로 전자가 더 나은 듯.

a.onclick = handleClick;
a.addEventListener("click", handleClick);

 

4. class를 변경/추가/제거하는 작업이 가능한데 총 2가지 방법이 있음. 후자가 더 안전하고 수정이 쉬움.

h1.className = "CLASS_NAME"
h1.classList.add("CLASS_NAME")
h1.classList.remove("CLASS_NAME")

// other methods are also useful
h1.classList.toggle("CLASS_NAME")

 

5. event에 의해 호출되는 함수는 기본적으로 event라는 argument가 추가된 상태로 작성됨.

handleClick(event) {
	event.preventDefault();
	console.log("blabla");
}

 

6. string concatenation할 때, string + string이 귀찮을 경우, python의 fstring과 같은 기능이 있음. ` 이용하는 것.

const text = `hello ${username}`;

 

7. 값을 저장하기 위한 브라우저 자체 기능으로 localStorage가 있음. 기타 Session storage 등도 있음.

localStorage.setItem('myCat', 'Tom');
localStorage.getItem('myCat');
localStorage.removeItem('myCat');

 

8. body flex-direction을 column으로 하고 나면 justify-content가 안 먹는 현상이 있는데. body에 height를 지정해주면 먹음.

body {
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: center;  
  align-items: center;
}

 

9. intervals and timeout. 일정 간격 반복 실행을 설정할 때와 일정 시간 대기 후 실행을 설정할 때 유용함. ms 단위. 

setInterval(func_name, 500);
setTimeout(func_name, 500);

 

10. 실시간 시간 관리는 data를 이용해서 함.

const date = new Date();
let miniute = date.getMinutes();
minute.padStart(2, "0");

 

11. .filter 함수를 이용해서 array 내 값을 선별할 수 있음

function customFilter(item){
    return item >=3;
}

array0.filter(customFilter); //full form
array0.filter((item)=> item>=3); //brief form
반응형

'Knowhow > Web' 카테고리의 다른 글

Django tips  (0) 2022.07.21
CSS tips 2  (0) 2022.06.20
CSS tips 1  (0) 2022.06.19
HTML tips  (0) 2022.06.12