JS Mini projects - Toggle Component

Seuling·2022년 6월 21일
0

FE

목록 보기
19/42

HTML

 <h1>Toggle Component</h1>
    <div class="faq-container">
      <div class="faq">
        <h3 class="faq-title">This is a title</h3>
        <p class="faq-text">This is a text</p>
        <button class="faq-toggle">
          <i class="fas fa-chevron-down"></i>
          <i class="fas fa-times"></i>
        </button>
      </div>

CSS


.faq-container {
  max-width: 600px;
  margin: 0 auto;
}

.faq {
  background-color: transparent;
  border: 1px solid #9fa4a8;
  border-radius: 10px;
  margin: 20px 0;
  padding: 30px;
  position: relative;
  overflow: hidden;
  transition: 0.3s ease;
}

.faq.active {
  background-color: #fff;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1), 0 3px 6px rgba(0, 0, 0, 0.1);
}

.faq-title {
  margin: 0 35px 0 0;
}

.faq-text {
  display: none;
  margin: 30px 0 0;
}

.faq.active .faq-text {
  display: block;
}

.faq-toggle {
  background-color: transparent;
  border: 0;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  padding: 0;
  position: absolute;
  top: 30px;
  right: 30px;
  height: 30px;
  width: 30px;
}

.faq-toggle:focus {
  outline: 0;
}

.faq-toggle .fa-times {
  display: none;
}

.faq.active .faq-toggle .fa-times {
  color: #fff;
  display: block;
}

.faq.active .faq-toggle .fa-chevron-down {
  display: none;
}

.faq.active .faq-toggle {
  background-color: #9fa4a8;
}

JS

  1. toggle 버튼 가져오기
  2. Nodelist 를 통해서 Loop 생성 (forEach)
  3. click이벤트 생성
  4. Toggle the active class on the parent node(.parentNode& classList.toggle())
const toggles = document.querySelectorAll(".faq-toggle");

toggles.forEach((toggle) => {
  toggle.addEventListener("click", () => {
    toggle.parentNode.classList.toggle("active");
  });
});

FAQ 작성 뿐만아니라, 토글은 많이 사용될 것 같다! CSS, JS를 가져와 사용하면 활용도 높을것같다!

profile
프론트엔드 개발자 항상 뭘 하고있는 슬링

0개의 댓글