1. script 선택자
document.getElementById(''); // ID로 html 호출
document.getElementsByClassName(''); // Class로 array 호출
document.querySelector(''); // css 방식으로 호출, array에서 첫번째 값만 가져옴
document.querySelectorAll(''); // css 방식으로 호출, array 전체
2. event listen
1) addEventListener("event name", function name);
- removeEventListener로 나중에 지울 수 있음
const title = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
title.style.color = "blue";
}
title.addEventListener("click",handleTitleClick);
//handleTitleClick(); 함수를 바로 실행 (괄호가 실행 버튼) 고로 click시에 실행할거니까 괄호를 빼야 함
//console.dir(title); 감지 가능한 이벤트들이 on뒤에 나옴 ex) onclick
2) on + event name = function name;
const title = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
title.style.color = "blue";
}
//title.addEventListener("click",handleTitleClick);
title.onclick = handleTitleClick;
*event 종류
- window에서 감지할 수 있는 것들
function handleWindowResize(){
document.body.style.backgroundColor = "tomato";
//body는 querySelector 이용하지 않아도 바로 접근 가능 (document에서 제공)
}
function handleWindowCopy(){
alert("You can't copy");
}
function handleWindowOffline(){
alert("SOS no WIFI!");
}
function handleWindowOnline(){
alert("ALL GOOD");
}
window.addEventListener('resize', handleWindowResize);
window.addEventListener('copy', handleWindowCopy);
window.addEventListener('offline', handleWindowOffline); //와이파이 연결 감지
window.addEventListener('online', handleWindowOnline);
3. if else 사용
- 클릭시 첫번째는 blue, 두번째는 tomato가 반복되게 만들기
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
const currentColor = h1.style.color; //getter, 최근 color값을 복사하는 역할, 의미론적으로 const로 선언하는 것이 적절
let newColor; //setter, 변수에 대입된 색상값을 h1.style.color에 최종적으로 할당하는 역할, 의미론적으로 추후에 값이 변경될 수 있으므로 let으로 선언하는 것이 적절
if(currentColor === "blue"){ //const니까 === 값일치를 찾는 것
newColor = "tomato"; //let이니까 = 새로운 값을 대입
}else{
newColor = "blue";
}
h1.style.color = newColor;
//newColor = h1.style.color가 아닌 이유?
//newColor에 값을 대입 하는 것이 아니라, if&else를 거쳐 할당된 newColor의 값을 h1.style.color에 대입하는 것
}
h1.addEventListener("click",handleTitleClick);
4. css 제어하기 (class 제어)
h1.className = 'active'; // class를 전부 삭제하고 대체
if(h1.classList.contains('active')){ // hasClass와 비슷
h1.classList.remove('active') ;
}else{
h1.classList.add('active');
}
h1.classList.toggle('active');
'Front-end > JavaScript' 카테고리의 다른 글
정규표현식 regular expression (0) | 2020.09.15 |
---|---|
UI와 API, 문서 (0) | 2020.09.15 |
모듈과 라이브러리 (0) | 2020.09.15 |
객체 object (0) | 2020.09.08 |
배열 array (0) | 2020.09.08 |