javascript 동적 Dialog Modal 만들기

2022. 6. 21. 23:23·dev/web
728x90
반응형
SMALL

안녕하세요. 

오늘은 javascript를 이용해 동적으로 Dialog Modal을 만들어 보도록 할게요. 

화면 중앙에 Dialog Modal 버튼을 만들고 버튼을 클릭하면 Dialog Modal 생성 후 Cancel 버튼을 눌러 

Dialog Modal을 다시 제거하도록 했습니다. 

 

우선 아래와 같이 버튼을 만듭니다. 

 

Dialog Modal button

<body>
<button onclick="showDialog()">Dialog Modal</button>
</body>

버튼을 클릭하면 showDialog 함수를 호출하고 함수해서 html 을 동적으로 body에 넣어 Dialog Modal을 표현합니다.

Dialog Modal

<div class="dialog">
    <div class="dialog__inner">
        <h1>Dialog Title</h1>
        <p>Dialog 내용입니다.</p>
        <div class="dialog__btn__wrap">
            <button id="cancel">Cancel</button>
            <button id="ok">OK</button>
        </div>
    </div>
</div>

위에 Dialog Modal HTML 코드를 Javascript에서 String 으로 만들고 DOMParser().parseFromString() 함수를 사용해

String DOM으로 변환합니다. 

변환된 DOM을 통해 dialog 클래스 찾아 document.body.appendChild() 함수를 통해 body에 붙여줍니다. 

cancel, ok 버튼을 클릭하면 document.body.removeChild() 함수를 통해 Dialog Modal를 제거합니다.

const showDialog = () => {

    const _html = `
        <div class="dialog">
            <div class="dialog__inner">
                <h1>Dialog Title</h1>
                <p>Dialog 내용입니다.</p>
                <div class="dialog__btn__wrap">
                    <button id="cancel">Cancel</button>
                    <button id="ok">OK</button>
                </div>
            </div>
        </div>
`

    const dom = new DOMParser().parseFromString(_html, 'text/html');
    const dialog = dom.querySelector(".dialog");
    document.body.appendChild(dialog)

    dialog.querySelector("#cancel").addEventListener("click", () => {
        document.body.removeChild(dialog)
    })

    dialog.querySelector("#ok").addEventListener("click", () => {
        // 로직 처리
        alert("OK");
        document.body.removeChild(dialog)
    })
}

 

각 버튼을 querySelector로 찾아 addEventListener('click') 을 통해 버튼 클릭을 조작할 수 있습니다. 

 

전체코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    *, *:before, *:after {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
    }

    body {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100vw;
        height: 100vh;
    }

    .dialog {
        width: 100vw;
        height: 100vh;
        position: fixed;
        left: 0;
        top: 0;
        background: rgba(0, 0, 0, .5);
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .dialog__inner {
        width: 800px;
        height: 200px;
        background: white;
        padding: 10px 16px;
        border-radius: 25px;
    }

    .dialog__inner h1 {
        font-size: 22px;
    }

    .dialog__inner p {
        text-align: center;
        height: 70px;
        line-height: 70px;
    }

    .dialog__btn__wrap {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 20px;
        margin-top: 40px;
    }

    .dialog__btn__wrap button {
        width: 100px;
        height: 25px;
    }

</style>
<body>
<button onclick="showDialog()">Dialog Modal</button>
</body>

<script>

    const showDialog = () => {

        const _html = `
            <div class="dialog">
                <div class="dialog__inner">
                    <h1>Dialog Title</h1>
                    <p>Dialog 내용입니다.</p>
                    <div class="dialog__btn__wrap">
                        <button id="cancel">Cancel</button>
                        <button id="ok">OK</button>
                    </div>
                </div>
            </div>
    `

        const dom = new DOMParser().parseFromString(_html, 'text/html');
        const dialog = dom.querySelector(".dialog");
        document.body.appendChild(dialog)

        dialog.querySelector("#cancel").addEventListener("click", () => {
            document.body.removeChild(dialog)
        })

        dialog.querySelector("#ok").addEventListener("click", () => {
            // 로직 처리
            alert("OK");
            document.body.removeChild(dialog)
        })
    }


</script>

</html>

위 코드를 통해 html을 만들어 동적으로 Dialog Modal을 만들어 Body에 추가/삭제하여 팔요에 따라 Dialog Modal을 사용 할 수 있습니다. 

728x90
반응형
LIST
저작자표시 (새창열림)

'dev > web' 카테고리의 다른 글

[NEXT] 프로젝트 생성하기 - 01  (3) 2023.09.21
Google 3rd Party oAuth2 device 구현하기  (6) 2022.07.21
jquery csv파일로 export 하기  (18) 2021.01.21
php 500 에러코드 출력  (6) 2021.01.18
Window 에서 Apache + PHP+ Mysql WebServer 만들기 3부 MySql 편  (14) 2021.01.10
'dev/web' 카테고리의 다른 글
  • [NEXT] 프로젝트 생성하기 - 01
  • Google 3rd Party oAuth2 device 구현하기
  • jquery csv파일로 export 하기
  • php 500 에러코드 출력
NCJ
NCJ
일상과 개발을 공유하고 소통하는 블로그입니다.
    반응형
    250x250
  • NCJ
    NCJ 프로그래밍
    NCJ
  • 전체
    오늘
    어제
    • ALL
      • dev
        • android
        • java
        • Spring Boot
        • node.js
        • MFC
        • react-native
        • web
        • 기타
        • vue
        • react
      • 일상
        • news
        • 요리
        • 영화
        • 드라마
        • 제품
        • 게임
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    던파 모바일 사전캐릭
    리니지w
    리니지w 이벤트
    갤럭시 버즈2
    갤럭시 워치 4
    사전캐릭
    리니지
    던파 사전캐릭
    던파 모바일 사전캐릭 생성
    게임
    다이어트
    삼성
    던파 모바일 서버오픈
    던파 출시일
    안드로이드
    리니지w 이벤트 안내
    CSS
    window webserver
    리니지w 오픈
    apache
    Web
    리니지W 사전예약
    java
    던파 서버 오픈
    갤럭시
    리니지w 보상
    Android
    코딩문제
    던파 캐릭생성
    php
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
NCJ
javascript 동적 Dialog Modal 만들기
상단으로

티스토리툴바