바닐라 JavaScript만을 사용하여 slideToggle 기능을 구현하고, 해당 기능이 끝나면 콜백 함수가 실행되도록 코드 구현.

 

바닐라js로 slideToggle 기능 구현

바닐라js로 slidetoggle 기능 구현

 

1. HTML 구조

2. JavaScript 구현

3. 코드분석

4. 동작예시

5. 결론

위의 목차를 클릭하면 해당 글로 자동 이동 합니다.

 

HTML 구조

<!DOCTYPE html>
<html lang="ko">
<head>
  <style>
    #box {
      width: 200px;
      background-color: #3498db;
      overflow: hidden; /* 내용이 넘치지 않도록 */
      transition: height 0.5s ease; /* 부드러운 전환 효과 */
    }

    .content {
      padding: 20px;
      color: white;
    }
  </style>
</head>
<body>
  <div id="box">
    <div class="content">이 내용은 슬라이드 토글됩니다.</div>
  </div>
  <button onclick="slideToggle(() => console.log('Slide Toggle 완료!'))">Slide Toggle</button>

  <script src="script.js"></script>
</body>
</html>
  • #box 요소는 초기에 height가 설정되지 않은 상태로 시작합니다.
  • transition 속성을 사용해 height가 부드럽게 변경되도록 설정합니다.
  • slideToggle 버튼을 클릭하면 요소가 열리거나 닫히고, 콜백 함수가 호출됩니다.

 

JavaScript 구현

// script.js

function slideToggle(callback) {
  const box = document.getElementById('box');
  const content = box.querySelector('.content');

  // 현재 높이를 계산
  const currentHeight = box.clientHeight;

  if (currentHeight === 0) {
    // 요소가 닫혀 있는 경우: 열기
    box.style.height = 'auto'; // 자동 높이로 설정
    const fullHeight = box.scrollHeight; // 전체 높이 계산
    box.style.height = '0px'; // 다시 0으로 설정
    setTimeout(() => {
      box.style.height = `${fullHeight}px`; // 전체 높이로 전환
    }, 10); // 약간의 지연 추가
  } else {
    // 요소가 열려 있는 경우: 닫기
    box.style.height = `${box.scrollHeight}px`; // 현재 높이로 설정
    setTimeout(() => {
      box.style.height = '0px'; // 0으로 전환
    }, 10); // 약간의 지연 추가
  }

  // transition이 끝나면 콜백 실행
  box.addEventListener('transitionend', () => {
    if (callback) callback();
  }, { once: true }); // 한 번만 실행
}

 

 

코드분석

1) 현재 높이 계산

const currentHeight = box.clientHeight;
  • clientHeight를 사용해 요소의 현재 높이를 계산합니다.
  • currentHeight === 0이면 요소가 닫혀 있는 상태입니다.

 

2) 요소 열기

box.style.height = 'auto'; // 자동 높이로 설정
const fullHeight = box.scrollHeight; // 전체 높이 계산
box.style.height = '0px'; // 다시 0으로 설정
setTimeout(() => {
  box.style.height = `${fullHeight}px`; // 전체 높이로 전환
}, 10); // 약간의 지연 추가
  • 요소가 닫혀 있는 경우, height를 auto로 설정하여 전체 높이를 계산합니다.
  • 다시 height를 0px로 설정한 후, setTimeout을 사용해 약간의 지연을 주고 전체 높이로 전환합니다.

 

3) 요소 닫기

box.style.height = `${box.scrollHeight}px`; // 현재 높이로 설정
setTimeout(() => {
  box.style.height = '0px'; // 0으로 전환
}, 10); // 약간의 지연 추가
  • 요소가 열려 있는 경우, 현재 높이를 설정한 후 setTimeout을 사용해 약간의 지연을 주고 0px로 전환합니다.

 

4) 콜백 실행

box.addEventListener('transitionend', () => {
  if (callback) callback();
}, { once: true }); // 한 번만 실행
  • transitionend 이벤트를 사용해 전환이 끝나면 콜백 함수를 실행합니다.
  • { once: true } 옵션을 사용해 이벤트 리스너가 한 번만 실행되도록 합니다.

 

동작예시

1. Slide Toggle:

  • "Slide Toggle" 버튼을 클릭하면 #box가 열리거나 닫힙니다.
  • 전환이 완료되면 콘솔에 "Slide Toggle 완료!"가 출력됩니다

 

결론

이 예제는 바닐라 JavaScript만을 사용하여 slideToggle 기능을 구현하고, 전환이 끝나면 콜백 함수를 실행하는 코드 입니다.

반응형

+ Recent posts