VANILLA_JS :Ch01

김정훈·2023년 7월 6일
0
post-thumbnail

변수(const, let, var)

var
재선언O, 재할당O
범위 : Function

let
재선언X, 재할당O
범위 : {}

const: 상수
재선언X, 재할당X
범위 : {}


function

//Before-Function
<div id="alert">
	<button onclick="document.getElemenyById('alert').style.display='block';">버튼클릭</button>
</div>

//After-Function
<div id="alert">
	<button onclick="openTest()">버튼클릭</button>
</div>

<script>
	function openTest(){
      document.getElementById('alert').style.display='block';
    }
</script>

JavaScript setTimeout

<div class="time">
  1초 이내 사라짐
</div>

<script>
    setTimeout(function(){
    	document.getElementByClassName("time").style.display = "none";
  	},1000)

// 1초마다 실행하는 함수 - SetInterval
	setInterval(function(){
  		console.log("반복");
	}, 1000);
</script>

JavaScript ifElse

if(True){
   console.log("True-실행")
}else{
	console.log("False-실행")   
}

JavaScript addEventListener

<button id="close">닫기</button>

<script>
  document.getElementById('close').addEventListener('click',function(){
  	document.getElementById('alert').style.display='none;
});

document.getElementByClassName("tab-button").eq(0).addEventListener('click', (e) => {
 document.getElementByClassName("tab-button").classList.remove("orange");
});
  
</script>

마우스 이벤트

이벤트 설명
click요소에 마우스를 클릭했을 때 이벤트가 발생
dbclick요소에 마우스를 더블클릭했을 때 이벤트가 발생
mouseover요소에 마우스를 오버했을 때 이벤트가 발생
mouseover요소에 마우스를 오버했을 때 이벤트가 발생
mouseout요소에 마우스를 아웃했을 때 이벤트가 발생
mousedown요소에 마우스를 눌렀을 때 이벤트가 발생
mouseup요소에 마우스를 떼었을 때 이벤트가 발생
mousemove요소에 마우스를 움직였을 때 이벤트가 발생
contextmenucontext menu(마우스 오른쪽 버튼을 눌렀을 때 나오는 메뉴)가 나오기 전에 이벤트 발생

키 이벤트

이벤트 설명
keydown키를 눌렀을 때 이벤트가 발생
keyup키를 떼었을 때 이벤트가 발생
keypress키를 누른 상태에서 이벤트가 발생

폼 이벤트

이벤트 설명
focus요소에 포커스가 이동되었을 때 이벤트 발생
blur요소에 포커스가 벗어났을 때 이벤트 발생
change요소에 값이 변경 되었을 때 이벤트 발생
submitsubmit 버튼을 눌렀을 때 이벤트 발생
resetreset 버튼을 눌렀을 때 이벤트 발생
selectinput이나 textarea 요소 안의 텍스트를 드래그하여 선택했을 때 이벤트 발생

로드 및 기타이벤트

이벤트 설명
load페이지의 로딩이 완료되었을 때 이벤트 발생
abort이미지의 로딩이 중단되었을 때 이벤트 발생
unload페이지가 다른 곳으로 이동될 때 이벤트 발생
resize요소에 사이즈가 변경되었을 때 이벤트 발생
scroll스크롤바를 움직였을 때 이벤트 발생

DOM_Document Object Model


JavaScript for, forEach, for_in

// for
for(let i=0; i<3; i++){
  console.log(i)
}

const tabButtons = document.querySelectorAll('.tab-button');

for (let i = 0; i < 3; i++) {
  tabButtons[i].addEventListener('click', function() {
    for (let j = 0; j < 3; j++) {
      tabButtons[j].classList.remove('orange');
      tabButtons[j].classList.remove('show');
    }
    tabButtons[i].classList.add('orange');
    tabButtons[i].classList.add('show');
  });
}

// forEach : Array에 붙일 수 있는 반복문_item의 수만큼 반복한다.
<div class="some-class">SomeThing Change</div>

<script>
 let item = [1, 2, 3];

 item.forEach(function (a) {
      const someClass = document.querySelectorAll('.some-class')[0];
      console.log(someClass);
      const plusChild = document.createElement('h1');
      plusChild.innerHTML="Something"+a;
      someClass.appendChild(plusChild);
        });
</script>
  
  
// for in : object자료 갯수만큼 반복문 돌려줌

let obj = {name: 'Kim', age: 18}

for (let key in obj){
  console.log(key);
  console.log(obj[key]);
}

JavaScript EventBubbling

: Event가 상위Html 요소로 퍼지는 현상을 말한다.

document.querySelector('.black-bg').addEventListener('click', function(e){
  	e.target; // 유저가 실제로 누른 것
  	e.currentTarget; // 이벤트리스너가 달린 곳
  	e.preventDefault(); // 이벤트가 발생안 한 것처럼 실행
  	e.stopPropagation(); // 상위요소로 EventBubbling 일어나지 않게

if(e.target == document.querySelector('.black-bg'){
   document.querySelector('.black-bg').classList.remove('show-modal');
}

EventBubble+Dataset사용

<ul class="list">
  <li class="tab-button" data-id="0">1</li>
  <li class="tab-button" data-id="1">2</li>
  <li class="tab-button" data-id="2">3</li>
</ul>
<script>
  // 반복문을 사용해도 되지만, 다음과 같이 dataset을 활요해도 된다.
  document.querySelector('.list').addEventListener(click, function(e){
    openTab(e.target.dataset.id)
  })
</script>
profile
WebDeveloper

0개의 댓글