개발세발

[새싹(SeSAC) 프론트엔드] day20 221111 본문

직업훈련/새싹(SeSAC)

[새싹(SeSAC) 프론트엔드] day20 221111

뉼👩🏻‍💻 2022. 11. 11. 09:02
728x90
반응형
SMALL

 

이벤트

: 마우스 클릭, 키보드 입력 등 사용자의 입력 행위나 문서 또는 브라우저의 상태 변화를 자바스크립트 코드에게 알리는 통지 

 

브라우저에서 발생하는 이벤트 종류

dblclick  마우스 더블클릭
change 라디오버튼 선택
resize 윈도우 크기 변경
keyup 누른 키를 놓을 때
keypress 키를 누를 때
reset reset 버튼 클릭시
submit submit 버튼 클릭시
click 마우스 클릭시 
load 로딩 완료시 

 

 

이벤트 리스너

onkeydown 사용자가 아무 키나 누르는 순간
onkeyup 사용자가 누른 키를 놓는 순간
onclick 사용자가 객체를 클릭할 때
ondblclick 객체에 더블 클릭할 때
onmousedown 마우스 버튼이 눌러지는 순간
onmouseover 마우스 커서가 객체 안으로 들어가는 순간
onmouseout 마우스 커서가 객체 밖으로 나가는 순간
onmouseup 눌러진 마우스 버튼을 놓는 순간
onwheel 마우스 휠을 굴리는 순간
onchange <input><select>등의 텍스트나 선택된 내용 등이 변할 때
onsubmit 사용자가 submit 버튼을 클릭하여 폼을 전송할 때 
onload 문서나 이미지의 로딩이 완료된 직후

➡️ addEventListener 로 사용할 때는 앞의 'on'을 빼주고 "keydown" 식으로 사용해주면 됨

 

(*)실습

[코드]

    <p>HTML 태그에 리스너 작성</p>
    <hr />
    <p
      onmouseover="this.style.backgroundColor='orange'"
      onmouseout="this.style.backgroundColor='white'"
    >
      마우스를 올리면 orange 색으로 변경
    </p>
    <p id="hoverEvent">자바스크립트로 마우스를 올리면 Red 색으로 변경</p>
let test = document.querySelector("#hoverEvent");


//익명함수
// : 함수 이름 없이 필요한 곳에 함수의 코드를 바로 작성 
test.addEventListener("mouseover", function () {
  test.style.backgroundColor = "red";
});

test.addEventListener("mouseout", function(){
  test.style.backgroundColor = "white";
})

 

[결과]

 

 

[코드]

  <body onload="init()">
    <p>HTML 태에 리스너 작성</p>
    <hr />
    <p id="test">마우스를 올리면 yellow 색으로 변경</p>

    <script src="js/practice02.js"></script>
  </body>
var p;

function init() {
  p = document.querySelector("#test");
  p.onmouseover = over;
  p.onmouseout = out;
}

function over() {
  p.style.backgroundColor = "yellow";
}

function out() {
  p.style.backgroundColor = "white";
}

 

 

 

mouseover

(*)실습

[과제]

function eventFunction(e) {
  console.log(e);
  //PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
  alert(e.type);
  //click
}

document.querySelector("#p").onmouseover = eventFunction;
//MouseEvent {isTrusted: true, screenX: 101, screenY: 171, clientX: 101, clientY: 35, …}

[결과]

 

 

 

 

addEventListener 

- 익명함수로 이벤트 리스너 작성

(*)실습

[코드]

let a = document.querySelector("#first");
let b = document.querySelector("#second");
let conclusion = document.querySelector(".result");
let btn = document.querySelector("#btn");
let result = 0;
btn.addEventListener("click", function () {
  result = eval(a.value);
  console.log(result);
  console.log(b.value);
  b.value = result;
});

[결과]

event object

: 발생한 이벤트에 관련된 다양한 정보를 담은 객체 

- 이벤트가 처리되고 나면 객체 소멸 

https://developer.mozilla.org/ko/docs/Learn/JavaScript/Building_blocks/Events#%EB%8B%A4%EB%A5%B8_%EC%9D%B4%EB%B2%A4%ED%8A%B8_%EA%B0%9C%EB%85%90%EB%93%A4

 

이벤트 입문 - Web 개발 학습하기 | MDN

이벤트(event)란 여러분이 프로그래밍하고 있는 시스템에서 일어나는 사건(action) 혹은 발생(occurrence)인데, 이는 여러분이 원한다면 그것들에 어떠한 방식으로 응답할 수 있도록 시스템이 말해주

developer.mozilla.org

 

- 매개변수 e 에 이벤트 객체 전달받는 형식으로 많이 사용됨 

 

 

 

 

 

onload

:window객체에 발생

- 웹 페이지의 로딩 완료 시 호출되는 이벤트 리스너 

 window.onload = alert('onload');

 <body onload="alert('onload');">

 

 

 

 

(*)실습 -  라디오 버튼 활용

<input type="radio"> 인 경우 

 - getElementsByName()으로 name 속성의 값 찾기

➡️ name속성이 같은 태그를 모두 찾아 컬렉션을 리턴

[코드]

let chkSum = document.getElementsByName("city");
let btn = document.querySelector("#btn");
let here = document.querySelector("#here");

btn.addEventListener("click", chkRadio);

console.log(chkSum);
function chkRadio() {
  let result = "";
  for (let i = 0; i < chkSum.length; i++) {
    if (chkSum[i].checked == true) {
      result = chkSum[i];
      console.log(result.textContent);
    }
    // here.textContent = result;
  }
}

 

[결과]

 

 

 

(*) 실습 - 체크박스 : 합계구하기

[코드]

let chkSum = document.getElementsByName("material");
let result = document.querySelector("#result");

let sum = 0;

function calc(chkUnit) {
  if (chkUnit.checked == true) {
    sum += parseInt(chkUnit.value);
  } else sum -= parseInt(chkUnit.value);
  result.value = sum;
}

[결과]

 

 

onchange = "함수()"

select에서 선택한 옵션이 변경되면 이를 인지하는 방법

(*)실습 - 선택한 항목에 따른 img출력

[코드]

// 선택된 항목에 따른 이미지 찾아오기

//교안에는 value에 이미지 경로가 지정되어 있었는데
// 아니면 value에 값을 주고 그거에 맞는 src를 찾는건 어떨까 ?

function drawImg() {
  let sel = document.getElementById("fruits");
  let img = document.getElementById("fruiteimgae");
  img.src = sel.options[sel.selectedIndex].value;
}

document.querySelector('');

[결과]

 

 

** options 

https://developer.mozilla.org/ko/docs/Web/API/HTMLSelectElement/selectedOptions

 

HTMLSelectElement.selectedOptions - Web API | MDN

The read-only HTMLSelectElement property selectedOptions contains a list of the <option> elements contained within the <select> element that are currently selected. The list of selected options is an HTMLCollection object with one entry per currently selec

developer.mozilla.org

 

 

 

 

 

**addeventlistener 사용시 무명함수(익명함수) 사용  ➡️ 코드가 짧거나 한 번만 사용하는 경우 

- 함수에 이름을 붙이는 것 ➡️ 여러 번 부르기 위함 

 

** window.open("사이트 주소", "이름을 쓰면 새창으로 열림/아니면 새탭으로 열림", "위치")

 

**innerHTML : html을 넣는 경우 

➡️ html로 넣어도 되고 글자만 써도 됨!! 

 

**innerText : 글자만 쓰는 경우

 

 

**e.target : 이벤트가 발생한 대상 객체 

 

 

 

 

 

 

 

 

 

새싹DT 기업연계형 프론트엔드 실무 프로젝트 과정 4주차 블로그 포스팅(금)

728x90
반응형