// 자바스크립트 변수명 규칙(camelCase)
const veryLongVariableName = 0
문자열 타입 숫자로 변환
paresInt("15") // 15
paresInt("aa") // NaN
// 대부분 사용(css selector)
document.querySelector(".hello h1")
// 만약 여러개가 조건에 맞을 경우 첫번째 요소 반환
// 조건에 맞는 여러개 가져오기, NodeList 반환
document.querySelectorAll(".hello h1")
HTML 요소 style 변경(inline-style)
const title = document.querySelector(".hello h1")
// style property 사용
title.style.color = 'blue'
이벤트 등록
title.addEventListener("click",handleTitleClick)
title.onclick = handleTitleClick
addEventListener는 여러 개의 이벤트 리스너를 추가할 수 있어서 권장한다.
- 이벤트 제거
title.removeEventListener("click",handleTitleClick)
window 이벤트
// 화면 크기 조절
window.addEventListener("resize",handleWindowResize)
// ctrl+c
window.addEventListener("copy",handleWindowCopy)
// wifi연결해제
window.addEventListener("offline",handleWindowOffline)
// wifi연결
window.addEventListener("online",handleWindowOnline)
클릭 시 css 변경 이벤트
HTML요소의 style속성에 직접 접근하여 css를 변경하는 것은 좋지 않다. 대신 classList를 사용한다.
function handleTitleClick(){
if(h1.style.color === "blue"){
h1.style.color = "tomato"
} else {
h1.style.color = "blue"
}
}
/*css*/
.clicked {
color: tomato
}
/*javascript*/
function handleTitleClick(){
h1.classList.toggle("clicked")
}
유저 입력 유효성 검사
<form>
<input
required
maxlength="15"
type="text"
/>
</form>
input의 유효성 검사 속성은 form 태그 안에서만 동작
form 태그 전송 방법(submit event 발생)
태그 기본 이벤트 막기(form,a)
function onLoginSubmit(e){
e.preventDefault()
}
localStorage를 통한 데이터 저장
// 저장
localStorage.setItem("key","value")
// 조회 (data || null)
const data = localStorage.getItem("key")
// 삭제
localStorage.removeItem("key")
반복적인 문자열 사용 시 상수화
const HIDDEN_CLASSNAME = "hidden"
const USERNAME_KEY = "username"
조건에 따른 렌더링
<!-- html -->
<div class="hidden">조건 1</div>
<span class="hidden">조건 2</span>
// css
.hidden{
display: none;
}
// javascript
const eldiv = document.querySelector("div")
const elspan = document.querySelector("span")
if(조건1){
eldiv.classList.remove("hidden")
} else if(조건2){
elspan.classList.remove("hidden")
}
시계 구현하기
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)
setInterval : 일정한 시간 간격으로 작업 수행
setTimeout : 일정한 시간 후 작업 한번 실행
문자열 Pad (글자수, 채울 문자)
// 앞에 추가 "1".padStart(2, "0") // "01" // 뒤에 추가 "1".padEnd(2, "0") // "10"
배열에서 랜덤으로 요소 가져오기
const data = arr[Math.floor(Math.random() * arr.length)]
랜덤 난수(min ~ max) 생성
const n = Math.floor(Math.random()*(max-min+1))+min
li 요소 제거하기
<ul>
<li>
<span>1</span>
<button>삭제</button>
</li>
</ul>
function deleteToDo(event){
// target : button
// parentElement : li
const li = event.target.parentElement
li.remove()
}
JavaScript 값이나 객체를 JOSN 문자열로 변환
JSON.stringify([1,2,3,4]) // "[1,2,3,4]"
JSON.stringify({ x: 5, y: 6 }) // "{"x":5,"y":6}"
JSON 문자열을 JavaScript 값이나 객체로 변환
JSON.parse("[1,2,3,4]") // [1,2,3,4]
JSON.stringify("{"x":5,"y":6}") // { x: 5, y: 6 }
ToDos 삭제 기능 구현
const newTodoObj = {
text: newTodo,
id: Date.now(), // 고유한 키 값으로 사용
}
키가 필요한 이유: "a"를 삭제하려고 할때 localStorage가 ["a","b","c","a"]와 같다면 어떤것을 삭제해야하는지 알 수 없다.
const li = document.createElement("li")
li.id = newTodoObj.id
toDos = toDos.filter((toDo) => toDo.id !== parseInt(li.id))
// li.id는 문자형이라 숫자형으로 변환
유저의 위치 반환(위도, 경도, GPS 등)
function onGeoOk(position) {
const lat = position.coords.latitude
const lon = position.coords.longitude
console.log("You live in", lat, lng)
}
function onGeoError() {
alert("Can't find you. No weather for you.")
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)
api 호출
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`
fetch(url)
.then(res => res.json())
.then(data => console.log)
HTML 요소 삽입 구조
<div id="weather"> <span></span> <span></span> </div>
const weather = document.querySelector("#weather span:first-child") const city = document.querySelector("#weather span:last-child")
배경이미지 css 애니메이션
@keyframes fadeIn{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
.bgImage{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
animation: fadeIn 0.5s linear;
}