노출된 모달창 혹은 레이어 팝업을 닫을 때
닫기 버튼 혹은 토글 버튼이 아닌 해당 영역외 영역을 눌러서 닫는 기능을 구현하고 싶을 때가 잇지요!!
오늘은 그걸 한번 해보려고 합니다!!
구별하기 편하게 알록달록 색을 넣어보았습니다ㅎㅎ
이런 모양의 모달창이고 HTML과 CSS 코드는 아래와 같습니다!
<div class="modal-wrap show">
<div class="modal">
<div class="title">Hello:)</div>
<div class="content"></div>
</div>
<div>
.modal-wrap{position:fixed;top:0;bottom:0;left:0;right:0;background:rgba(0,0,0,.7);display:none;}
.modal-wrap.show{display:block;}
.modal{width:500px;height:300px;position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;background:#fff;text-align:center;padding:30px;box-sizing:border-box;}
.modal .title{margin:0 0 30px;background:salmon}
.modal .content{background:skyblue;height:200px;}
이제 javascirpt를 넣을게요~
click 이벤트를 통해 얻을 수 있는 event 정보를 이용해야합니다.
그 중에서도 event.target!! target이 누군지에 따라 작동하게 하면 됩니다.
방법 1.
$('.modal-wrap').click(function(e){
if( !$(e.target).hasClass('modal')){
$(this).removeClass('show');
}
});
See the Pen Untitled by Younjung Jeong (@jojv) on CodePen.
간단하게 해결된듯 보이지만, modal 안에 title(분홍색 부분), content(하늘색 부분)을 클릭하면 모달창이 닫히게 되어
완전한 해결 방안은 아닌듯 합니다.
방법 2.
$('.modal-wrap').click(function(e){
if( !$('.modal-wrap').has( e.target ).length){
$(this).removeClass('show');
}
});
See the Pen Untitled by Younjung Jeong (@jojv) on CodePen.
아주 잘됩니다 ㅎㅎ
그러나 아무래도 간단한 구조여서 오류가 없는 건 아닐까 하여 제일 베스트는 두가지를 모두 조건으로 걸어보았습니다!
방법 3.
$('.modal-wrap').click(function(e){
if( !$(e.target).hasClass('modal') && !$('.modal-wrap').has( e.target ).length){
$(this).removeClass('show');
}
});
See the Pen Untitled by Younjung Jeong (@jojv) on CodePen.
오류날 확률이 가장 적을듯합니다!!
e.target을 이용해 특정영역을 제외한 영역 클릭시 동작하는 코드를 작성해봤습니다~
혹시나 더 좋은 방법이나 수정해야할 사항이 있다면 꼭 알려주세요~ㅎㅎ
열심히 배우겠습니다!!
글 읽어 주셔서 감사합니다.
'Javascript' 카테고리의 다른 글
[GSAP] 스크롤 위치에 따라 탭메뉴 On & Off (ScrollTrigger) (4) | 2023.03.08 |
---|---|
[Javascript] 버튼 클릭 한번으로 모든 체크 박스 체크 해제하기 (4) | 2023.03.07 |
[javascript] PIP기능을 구현해보자!(쉬움주의) (4) | 2023.02.22 |
[javascript] 요소 클릭 시 텍스트 input value값으로 넣기(예시 : 배송시 요청 사항을 선택해주세요.) (0) | 2023.02.09 |
[javascript] swiper slide 2개 연동하여 제어하기 (0) | 2023.02.03 |