javaScript/Vanilla JS

Vanilla JS 간단한 모달창 열기/닫기

mooyou 2025. 4. 22. 23:21
728x90
300x250
SMALL

 

jQuery

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
  .modal{display: none;position: fixed;top: 0;left: 0;
  width: 100%;height: 100%;background: rgba(0,0,0,0.5);}
  .modal-content{background: #fff;margin: 15% auto;padding: 20px;width: 300px;}
  .modal-content .close{cursor: pointer;}
</style>

<button class="open">모달 열기</button>
<div id="modal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>모달 내용입니다.</p>
  </div>
</div>

<script>
$('.open').click(function(){
  $('#modal').fadeIn();
});
$('.close').click(function(){
  $('.modal').fadeOut();
})
</script>

 

 

Vanilla JS

<style>
  .modal{display: none;position: fixed;top: 0;left: 0;
  width: 100%;height: 100%;background: rgba(0,0,0,0.5);}
  .modal-content{background: #fff;margin: 15% auto;padding: 20px;width: 300px;}
  .modal-content .close{cursor: pointer;}
</style>

<button class="open">모달 열기</button>
<div id="modal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>모달 내용입니다.</p>
  </div>
</div>

<script>
document.querySelector(".open").onclick = function(){
  document.getElementById("modal").style.display ="block";
}
document.querySelector(".close").onclick = function(){
  document.getElementById("modal").style.display ="none";
}
</script>

 

 

 

 

 

  • 제이쿼리에서 fadeIn() / fadeOut()은 서서히 나타나고 사라지는 부드러운 효과가 나타난다,
  • 하지만 Vanilla JS 코드는 단순히 display:none 했다가 display:block 하는 효과로 애니메이션 효과가 없다.
  • Vanilla JS로도 fadeIn / fadeOut 효과를 구현할 수 있지만 코드가 길고 번거롭다.

바닐라 JS로 fadeIn / fadeOut 효과 만들기

function fadeIn(el, duration = 400) {
  el.style.opacity = 0;
  el.style.display = 'block';
  let last = +new Date();
  let tick = function() {
    el.style.opacity = +el.style.opacity + (new Date() - last) / duration;
    last = +new Date();

    if (+el.style.opacity < 1) {
      requestAnimationFrame(tick);
    }
  };
  tick();
}

function fadeOut(el, duration = 400) {
  el.style.opacity = 1;
  let last = +new Date();
  let tick = function() {
    el.style.opacity = +el.style.opacity - (new Date() - last) / duration;
    last = +new Date();

    if (+el.style.opacity > 0) {
      requestAnimationFrame(tick);
    } else {
      el.style.display = 'none';
    }
  };
  tick();
}

 

사용법

document.querySelector(".open").onclick = function(){
  const modal = document.getElementById("modal");
  fadeIn(modal);
}

document.querySelector(".close").onclick = function(){
  const modal = document.getElementById("modal");
  fadeOut(modal);
}

 

 

728x90
반응형
LIST