본문 바로가기
프론트엔드/javascript

collapse toggle(show&hide) vanilla javascript

by 느바 2022. 1. 11.
반응형

collapse toggle(show&hide) vanilla javascript

js

 

'접혔다 펼쳤다' 를 자바스크립트로 구현할 때,

단순히 '있다 없다' 를 구현하기는 쉽지만,

자연스럽게 '접혔다 펼쳤다' 를 구현하기는 생각보다 까다롭다.

 

jquery 로 구현할 때는 자연스럽게 구현하는 것에 대한 고민을 할 필요가 없다.

$(document).ready(function(){
  $("button").click(function(){
    $("p").toggle(1000);
  });
});

jquery 라이브러리 도움 없이

pure javascript로만 자연스러운 toggle 기능을 구현할 때 어려운 점은,

펼쳐진 영역의 height 값을 알아내기가 까다롭다는 점이다. (height auto 이면 transition이 일어나지 않는다.)

 

stackoverflow 에서 동일한 이슈에 얼마나 많은 답변이 달렸는지보자.

https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css

 

How can I transition height: 0; to height: auto; using CSS?

I am trying to make a <ul> slide down using CSS transitions. The <ul> starts off at height: 0;. On hover, the height is set to height:auto;. However, this is causing it to simply appea...

stackoverflow.com

 

문제의 핵심 자연스럽게 height 0 -> height auto 로 변형하기

 

방법1

위 stackoverflow 이슈에 달린 답변을 보면, height 대신 max-height를 사용하는 방법이 나온다.

하지만, 적절한 max-height 값을 설정하는 것도 고민이다.

맘편하게 max-height 을 100vh로 줄 수도 있지만, 펼쳐진 영역 크기가 100vh을 넘어간다면 이또한 맞지 않다.

(무작정 크게 줄 순 없지 않은가)

 

방법2

물론, 펼쳐진 영역의 height를 직접 계산하는 방법도 있다. 

element.outerHeight();

 

방법3

최대한 간단하게, 주변의 어떤 것에도 영향을 덜 받거나 덜 주는 방법으로 채택한 방법은,

펼쳐진 영역의 padding 을 이용하는 것이다.

접혔을 때는 padding 0, 펼쳤을 때는 padding 20px

.expansionpanel .expander-content-wrapper{
  /* max-height:0; */
  height:0;
  padding:0 20px;
  overflow:hidden;
  transition:padding 0.2s ease;
}
.expansionpanel.expanded .expander-content-wrapper{
  /* max-height:100vmax; */
  height:auto;
  padding:20px;
}

 

 

반응형