JavaScript 접기 펼치기 (샘플 코드)
HTML의 <div>
요소 등을 접기 펼치기 하는 기능을 구현하는 순수한 JavaScript(바닐라 JS)로 작성된 샘플 코드입니다.
접히거나 펼쳐지는 움직임은 보통 목차, 더보기(Read More), FAQ(자주 묻는 질문과 그에 대한 답을 정리해 놓은 페이지) 등에서 자주 사용됩니다. 웹 브라우저라는 한정된 공간에서 우선 필요 없는 부분은 숨길 수 있어 웹 페이지를 보다 효율적으로 구성할 수 있습니다. 사용자의 필요에 따라 열고 닫을 수 있으면 되는 것입니다.
어렵지 않고 간단한 코드이지만, 막상 작성하려면 아무래도 조금 머리를 써야 하고 시간이 들기 마련입니다. 중요한 로직에만 집중하는게 효율적입니다. 본문의 샘플 코드를 참고하세요.
펼치고 접기
[샘플 코드]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
#toc-content { | |
display: none; | |
} | |
#toc-toggle { | |
cursor: pointer; | |
color: #2962ff; | |
} | |
#toc-toggle:hover { | |
text-decoration: underline; | |
} | |
</style> | |
목차 [<span id="toc-toggle" onclick="openCloseToc()">보이기</span>] | |
<ol id="toc-content"> | |
<li>HTML</li> | |
<li>CSS</li> | |
<li>JavaScript</li> | |
</ol> | |
<script> | |
function openCloseToc() { | |
if(document.getElementById('toc-content').style.display === 'block') { | |
document.getElementById('toc-content').style.display = 'none'; | |
document.getElementById('toc-toggle').textContent = '보이기'; | |
} else { | |
document.getElementById('toc-content').style.display = 'block'; | |
document.getElementById('toc-toggle').textContent = '숨기기'; | |
} | |
} | |
</script> |
[코드 설명]
목차를 보이고 숨기는 기능입니다. 더보기(Read More) 기능 등에 응용할 수 있습니다. 그리고 보이기·숨기기 토글에서 가끔
<a href="javascript:함수명()">
식으로 작성하는 경우가 있는데 HTML의 <a>
요소는 적절한 URL을 사용해서 이동하는 용도로만 사용하는 것이 올바르다고 합니다.[실행 결과]
목차 [보이기]
- HTML
- CSS
- JavaScript
여러 개를 펼치고 접기
[샘플 코드]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
.answer { | |
display: none; | |
padding-bottom: 30px; | |
} | |
#faq-title { | |
font-size: 25px; | |
} | |
.faq-content { | |
border-bottom: 1px solid #e0e0e0; | |
} | |
.question { | |
font-size: 19px; | |
padding: 30px 0; | |
cursor: pointer; | |
border: none; | |
outline: none; | |
background: none; | |
width: 100%; | |
text-align: left; | |
} | |
.question:hover { | |
color: #2962ff; | |
} | |
[id$="-toggle"] { | |
margin-right: 15px; | |
} | |
</style> | |
<span id="faq-title">자주 묻는 질문(FAQ)</span> | |
<div class="faq-content"> | |
<button class="question" id="que-1"><span id="que-1-toggle">+</span><span>'HTML'이란 무엇인가요?</span></button> | |
<div class="answer" id="ans-1">하이퍼텍스트 마크업 언어(HyperText Markup Language)입니다.</div> | |
</div> | |
<div class="faq-content"> | |
<button class="question" id="que-2"><span id="que-2-toggle">+</span><span>'CSS'란 무엇인가요?</span></button> | |
<div class="answer" id="ans-2">캐스케이딩 스타일 시트(Cascading Style Sheets)입니다.</div> | |
</div> | |
<div class="faq-content"> | |
<button class="question" id="que-3"><span id="que-3-toggle">+</span><span>'JavaScript'란 무엇인가요?</span></button> | |
<div class="answer" id="ans-3">자바스크립트는 객체(Object)를 기초로 하는 스크립트 프로그래밍 언어입니다.</div> | |
</div> | |
<script> | |
const items = document.querySelectorAll('.question'); | |
function openCloseAnswer() { | |
const answerId = this.id.replace('que', 'ans'); | |
if(document.getElementById(answerId).style.display === 'block') { | |
document.getElementById(answerId).style.display = 'none'; | |
document.getElementById(this.id + '-toggle').textContent = '+'; | |
} else { | |
document.getElementById(answerId).style.display = 'block'; | |
document.getElementById(this.id + '-toggle').textContent = '-'; | |
} | |
} | |
items.forEach(item => item.addEventListener('click', openCloseAnswer)); | |
</script> |
[코드 설명]
FAQ(Frequently Asked Questions, 자주 묻는 질문들) 페이지에서 흔히 볼 수 있는 여러 개를 각각 펼치고 접는 기능입니다. 여러 개를 동시에 모두 펼치고 접는 기능은 보통 없지만, 구현하려면 위 코드에서는 answer 클래스를 활용하면 됩니다.
[실행 결과]
자주 묻는 질문(FAQ)
하이퍼텍스트 마크업 언어(HyperText Markup Language)입니다.
캐스케이딩 스타일 시트(Cascading Style Sheets)입니다.
자바스크립트는 객체(Object)를 기초로 하는 스크립트 프로그래밍 언어입니다.
JavaScript 없이 펼치고 접기
[샘플 코드]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
summary { | |
cursor: pointer; | |
} | |
/* 삼각형 없애기 | |
summary { | |
list-style: none; | |
} | |
summary::-webkit-details-marker { | |
display: none; | |
} | |
*/ | |
</style> | |
<!-- 처음부터 보이려면, <details open> --> | |
<details> | |
<summary>'XHTML'의 의미</summary> | |
<p>XHTML(Extensible HyperText Markup Language)은 확장성이 있는 하이퍼텍스트 마크업 언어이다.</p> | |
</details> |
[코드 설명]
HTML의
<details>
와 <summary>
요소로 JavaScript 없이 펼치고 접기가 가능합니다. 회전하면서 열림 또는 닫힘 상태를 나타내는 삼각형이 기본적으로 붙어 있습니다. 그리고 닫힌 상태가 기본입니다. 삼각형을 없애거나, 열린 상태를 기본으로 하려면 주석 처리된 부분을 확인하세요.[실행 결과]
'XHTML'의 의미
XHTML(Extensible HyperText Markup Language)은 확장성이 있는 하이퍼텍스트 마크업 언어이다.
참고하여 공부하는 중에 두번째 여러개를 펼치고 접는 코드가 익스플로러에서는 안먹는데 해결할 방법이 있을까요 ?
답글삭제이제 익스플로러는 대응하지 않아도 된다고 생각하는데
삭제아마도 '화살표 함수' 때문일 겁니다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions
삭제맨 밑에 '브라우저 호환성' 보시면 Internet Explorer는 No support라고 되어 있네요.
소스코드가 너무 좋아서 공부로 사용하려고 하는데 질문 하나 해도 될까요??
답글삭제여러개 펼치고 접기 부분에서
const answerId = this.id.replace('que', 'ans');
이 부분이 잘 이해가 안가는데 설명이 가능하실까요??
단순히 replace 안에 있는 두 가지를 바꾼다는 의미인가요??
좋은 코드 감사합니다 :)
답글삭제혹시 다른 질문 클릭해서 답변 열었을때 동시에 위에 열었던 답변을 닫게 할 수 있나요??
답글삭제