본문 바로가기

자바스크립트

[자바스크립트] - 이벤트 종류 / 간단한 이벤트 실습

이벤트의 종류

(전부 소문자이다) 이것말고도 훨씬 많다. 검색해서 사용

 

1. 마우스 이벤트 

: 마우스를 이용해 버튼이나 휠 버튼을 조작할 때 사용한다. 아래 종류보다 더 많으니 원할 때 찾아보면 된다. 

종류 설명
- ★ click  사용자가 html 요소를 클릭할 때 이벤트가 발생한다. 
- dblclick 사용자가 html요소를 더블클릭할 때 이벤트가 발생한다. 
- mousedown  사용자가 요소 위에서 버튼을 눌렀을 때 이벤트가 발생한다. (click이랑 거의 동일해서 잘 안쓴다)
- ★ mousemove 사용자가 요소 위에서 마우스 포인터를 움직일 때 이벤트가 발생한다.
( 마우스 포인터 자체를 원하는 요소를 바꿀 때나 마우스를 따라다니는 요소를 만들 때 사용한다. 움직이는 배경이 마우스를 따라다닐때, 쇼핑몰에 이미지 마우스 올렸을 때 이미지 확대될 때 등)
- mouseout 마우스 포인터가 요소를 벗어날 때 이벤트가 발생한다. 
- ★ mouseover 마우스 포인터가 요소 위로 옮겨질 때 이벤트가 발생한다. 
- mouseup 사용자가 요소 위에 놓인 마우스 버튼에서 손을 뗄 때 이벤트가 발생한다. 
- ★ wheel 사용자가 마우스 휠을 움직이면 이벤트가 발생한다. ( 이벤트 객체랑 같이 써야한다. )

 


2. 키보드 이벤트

: 키보드에서 특정 키를 조작할 때 이벤트가 발생한다. keydown 정도만 기억하면 된다. 

종류 설명
- keydown 사용자가 키를 누르는 동안 이벤트가 발생한다. 종종 쓰는데 검색창에서 엔터치면 검색되야할 때 이거 쓴다. 돋보기아이콘에 submit이 들어있어서, 엔터 누르면 돋보기 누른것처럼 실행하라 이렇게 할 때 종종 쓴다.)
- keypress 사용자가 키를 눌렀을 때 이벤트가 발생한다. 
- keyup  사용자가 키에서 손을 뗄 때 이벤트가 발생한다.

 

3. 문서 로딩 이벤트

: 서버에서 웹 문서를 가져오거나 문서를 위 아래로 스크롤하는 등 웹 문서를 브라우저 창에 보여주는 것과 관련된 이벤트이다. 

종류 설명
 - abort 문서가 완전히 로딩되기 전에 불러오기를 멈췄을 때 이벤트가 발생한다. 
- ★ error   문서가 정확히 로딩되지 않았을 때 이벤트가 발생한다. 
- ★ load 문서 로딩이 끝나면 이벤트가 발생한다. (페이지에 들어가면 이벤트가 뜰 때)
 - resize 문서 화면 크기가 바뀌었을 때 이벤트가 발생한다. 
- ★ scroll  문서 화면이 스크롤 되었을 때 이벤트가 발생한다. 
- upload 문서에서 벗어날 때 이벤트가 발생된다. 해당하는 탭을 껐을 때 이벤트가 발생.

4. 폼 이벤트

: 로그인, 검색, 게시판, 설문조사처럼 사용자가 입력하는 모든 요소에 내용을 입력하면 이벤트가 발생

종류 설명
- ★ blur 폼 요소에서 포커스를 잃었을 때 이벤트가 발생한다. (focus의 반대상태. 회원가입할 때 필수요소를 안쓰고 벗어났을때 알려줄때 등 사용)
- ★ change  목록이나 체크 상태 등이 변경되면 이벤트가 발생한다. input, select, textarea 태그에서 사용.
(알림동의 선택 체크안했을 때 알림 안보내야하니깐 그럴때 사용, 광고성 수신동의 등)
- ★ focus  폼 요소에 포커스가 놓였을 때 이벤트가 발생한다. label, input,  select, textarea, button 태그에서 사용
- ★ reset  폼이 리셋되었을 때 이벤트가 발생한다. (깡통버튼을 만들어놨다가 기능을 나중에 삽입할 때 등 사용)
- ★ submit  submit버튼을 클릭했을 때 이벤트가 발생한다. (회원탈퇴할 때 정말 탈퇴하겠습니까? 이렇게 한번 더 물을 때 사용)

 

예제 1 ) 클릭하면 배경색이 바뀌는 이벤트 

 

html

 
 <div class="btnbox">
      <div class="box" onclick="changeBg('green')">green</div>
      <div class="box" onclick="changeBg('orange')">orange</div>
      <div class="box" onclick="changeBg('tomato')">tomato</div>
  </div>
 
    <div id="colorbox"></div>
 

css

 <!-- css -->
    <style>
      .btnbox {
        width: 500px;
        height: fit-content;
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        justify-content: center;
      }
      .box {
        width: 150px;
        height: 40px;
        border: 1px solid #777;
        text-align: center;
        line-height: 36px;
        border-radius: 20px;
      }
      #colorbox {
        width: 500px;
        height: 300px;
        border: 1px solid #777;
      }
    </style>

 

자바스크립트

      //클릭하면 배경이 바뀌는 이벤트
      //함수를 호출할 때 쓴 인수 green,orange,tomato가  color라는 매개변수에 들어간다. 그리고 백그라운드 컬러를 매개변수로 받은 것으로 바꾸겠다.
 
      function changeBg(color) {
 
        let colorBox = document.querySelector("#colorbox");
        colorBox.style.backgroundColor = color;
      }
 

꼭 query로 불러오지 않아도 된다. 


예제 2) 상세설명보기 버튼을 누르면 설명이 나오고 X버튼을 누르면 사라지고 상세설명보기 버튼 다시 나타내기

html

 <div class="bigbox">
      <div class="imgbox">
        <img src="./img/food.jpg" alt="음식" />
        <button type="button" onclick="showDetail()">상세설명 보기</button>
      </div>
      <div class="textbox">
        <h3>딸기 샐러드</h3>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere nemo
          optio quia vero, dolore iusto maxime alias labore fuga reprehenderit
          distinctio quos amet architecto esse consequuntur? Non minus tempore
          incidunt.
        </p>
        <button type="button" onclick="hideDetail()">X</button>
      </div>
    </div>

css

 <!-- css -->
    <style>
      .bigbox {
        width: fit-content;
        height: fit-content;
      }
      .imgbox {
        width: 500px;
        height: 300px;
        overflow: hidden;
        position: relative;
      }
      .imgbox img {
        max-width: 100%;
        position: absolute;
        top: -220px;
        left: 0;
      }
      .imgbox > button {
        position: absolute;
        left: 20px;
        bottom: 20px;
        border: none;
        padding: 5px 16px;
        border-radius: 20px;
        background-color: #ffffff;
        cursor: pointer;
      }
      .textbox {
        width: 500px;
        height: 300px;
        box-sizing: border-box;
        padding-left: 20px;
        display: none; /*숨기기-스르륵할려면 오버플로우히든으로 숨겨야한다.*/
      }
      .textbox > button {
        left: 20px;
        bottom: 20px;
        border: none;
        padding: 5px 10px;
        border-radius: 20px;
        background-color: #000000;
        cursor: pointer;
        color: #fff;
      }
    </style>

자바스크립트

 <!-- 자바스크립트 -->
    <script>
      //상세 설명을 화면에 표시하는 함수
      //디스플레이논으로 숨겨놓은 걸 디스플레이 블럭으로 다시 보여줘라
      //그리고 상세설명 보기 버튼은 숨겨라
      function showDetail() {
        document.querySelector(".textbox").style.display = "block";
        document.querySelector(".imgbox > button").style.display = "none";
      }

      //상세 설명을 화면에서 숨기는 함수
      function hideDetail() {
        document.querySelector(".textbox").style.display = "none";
        document.querySelector(".imgbox > button").style.display = "block";
      }
    </script>

* 불러올 때 css랑 똑같이 불러오면 된다. ex) .imgbox > button 이렇게 똑같이 불러오면 된다. 


예제 3) 위의 예제를 좀 더 효율적으로 바꿔보기

상세설명 보기 버튼 누르면 펼쳐지고 누르면 다시 사라지고- 

html

 <div class="bigbox">
      <div class="imgbox">
        <img src="./img/food.jpg" alt="음식" />
        <button type="button" onclick="showDetail(1)">상세설명 보기</button>
      </div>
      <div class="textbox">
        <h3>딸기 샐러드</h3>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere nemo
          optio quia vero, dolore iusto maxime alias labore fuga reprehenderit
          distinctio quos amet architecto esse consequuntur? Non minus tempore
          incidunt.
        </p>
      </div>
    </div>

css

  .bigbox {
        width: fit-content;
        height: fit-content;
      }
      .imgbox {
        width: 500px;
        height: 300px;
        overflow: hidden;
        position: relative;
      }
      .imgbox img {
        max-width: 100%;
        position: absolute;
        top: -220px;
        left: 0;
      }
      .imgbox > button {
        position: absolute;
        left: 20px;
        bottom: 20px;
        border: none;
        padding: 5px 16px;
        border-radius: 20px;
        background-color: #ffffff;
        cursor: pointer;
      }
      .textbox {
        width: 500px;
        height: 300px;
        box-sizing: border-box;
        padding-left: 20px;
        display: none; /*숨기기-스르륵할려면 오버플로우히든으로 숨겨야한다.*/
      }
      .textbox > button {
        left: 20px;
        bottom: 20px;
        border: none;
        padding: 5px 10px;
        border-radius: 20px;
        background-color: #000000;
        cursor: pointer;
        color: #fff;
      }

자바스크립트

 //좀 더 효율적인 함수 만들기

      let result = true;
      //상세 설명을 화면에 표시하는 함수
      function showDetail() {
        if (result == true) {
          document.querySelector(".textbox").style.display = "block";
          result = false;
        } else {
          document.querySelector(".textbox").style.display = "none";
          result = true;
        }
      }

result라는 변수를 만들어서 현재 상태를 저장해놓은 것.