티스토리 뷰

Javascript & Node

Bootbox JS 소개

터프남 2022. 7. 4. 10:54
728x90

옛날 어딘가에 정리했었던거 옮김.

Bootstrap Modal을 쉽게 사용하게 해주는 BootBox.js 예제

Bootbox.js 소개

Bootbox.js는 필요한 DOM 요소 또는 JS 이벤트 핸들러를 생성, 관리 또는 제거하는 것에 대해 걱정할 필요없이 부트 스트랩 모달을 사용하여 프로그래밍 방식 대화 상자를 만들 수있는 작은 JavaScript 라이브러리이다.

공식사이트

Bootbox.js

사용방법

  • CDN

https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js

  • 다운로드

위의 공식사이트에가서 다운로드 받아서 본인의 소스에 추가해서 사용하면 된다.

Bootbox.js는 bootstrap의 모달을 이용하는 것이므로 bootstrap.js가 필요하고 bootstrap의 모달기능을 사용하기위해서는 jquery가 필요하므로 Bootbox.js를 사용하기 위해서는 bootstrap과 jquery를 추가해주어야 한다.

보통 이런 상황을 Bootbox.js가 bootstrap과 jquery에 의존한다고 한다.

예제

Bootbox.js는 크게 4가지 function을 사용할 수 있다.

  • Alert
  • prompt
  • confirm
  • Custom dialog

이제부터 각각 사용법을 간단한 예제로 작성해 보자!!

Alert 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bootbox Example</title>
    <!-- css dependencies -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>

    <div>
        <button class="btn btn-info" id="btn_click">클릭</button>
    </div>
<!-- JS dependencies -->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>

<!-- bootbox code -->
<script src="js/bootbox.min.js"></script>
<script>
    $(document).ready(function (e) {
        $("#btn_click").on("click", function () {
            bootbox.alert("This is the default alert!");
        });
    });
</script>
</body>
</html>

기본 사용법

bootbox.alert("Your message here…")

alert()의 메시지를 작성하는 부분에는 HTML의 태그를 포함시켜서 나타낼 수 도 있다.

bootbox.alert("Your message <b>here…</b>")

또 다른 사용법으로는 메시지 안에 콜백함수를 넣을 수가 있다.

bootbox.alert("Your message here…", function(){ /* your callback code */ })

옵션 예제

bootbox.alert({ 
  size: "small",
  title: "Your Title",
  message: "Your message here…", 
  callback: function(){ /* your callback code */ }
})

Bootbox 홈페이지에 가면 alert에 추가할 수 있는 옵션들을 문서로 제공하고 있다. Dialog Option

위에 나와있는 옵션 말고도 여러가지 옵션이 존재한다.

Confirm 예제

confirm function은 그냥 자바스크립트의 confirm 메소드와 비슷한 기능을 하는 function 같다. 실행을하면 기존 자바스크립트의 confirm 처럼 확인과 취소 버튼이 나온다. 확인을 누르면 true를 반환하고 취소를 누르면 false를 반환한다. 그리고 그냥 esc키로 dialog box를 끌 경우는 그냥 취소를 클릭한 것과 동일하게 처리한다.

confirm dailog는 callback function이 필수 요소다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bootbox Example</title>
    <!-- css dependencies -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>

<div>
    <button class="btn btn-info" id="btn_click">클릭</button>
</div>
<!-- JS dependencies -->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>

<!-- bootbox code -->
<script src="js/bootbox.min.js"></script>
<script>
    $(document).ready(function (e) {
        $("#btn_click").on("click", function () {
            bootbox.confirm("This is the default confirm!", function(result){
                console.log('This was logged in the callback: ' + result);
            });
        });
    });
</script>
</body>
</html>

여기에서는 확인 취소의 true false 값이 result로 들어간다.

기본 사용법

bootbox.confirm("Are you sure?", function(result){ /* your callback code */ })

옵션을 추가한 사용법

bootbox.confirm({ 
  size: "small",
  message: "Are you sure?", 
  callback: function(result){ /* result is a boolean; true = OK, false = Cancel*/ }
})

Prompt 예제

prompt function도 confirm과 거의 같다. 다른 점은 confirm은 확인 취소 버튼만 있지만 prompt는 input box가 추가로 들어가 있다는 점 빼고는 같다. 사용방법도 같은 것 같다.

promprt dailog도 callback fucntion이 필수다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bootbox Example</title>
    <!-- css dependencies -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>

<div>
    <button class="btn btn-info" id="btn_click">클릭</button>
</div>
<!-- JS dependencies -->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>

<!-- bootbox code -->
<script src="js/bootbox.min.js"></script>
<script>
    $(document).ready(function (e) {
        $("#btn_click").on("click", function () {
            bootbox.prompt("This is the default prompt!", function(result){ alert(result); });
        });
    });
</script>
</body>
</html>

dialog에 나온 input box의 값이 result로 들어온다.

기본 사용법

bootbox.prompt("What is your name?", function(result){ /* your callback code */ })

옵션 추가 사용법

bootbox.prompt({ 
  size: "small",
  title: "What is your name?", 
  callback: function(result){ /* result = String containing user input if OK clicked or null if Cancel clicked */ }
})

prompt dialog는 기본으로 하나의 input box를 가지고 있다. 그런데 여기서 prompt만 쓸 수 있는 옵션으로 다른 input type으로 수정할 수 있다.

속성명설명valuevalue 옵션을 사용해서 prompt의 초기 값을 설정할 수 있다.inputTypeprompt dialog의 input type을 변경한다. text (기본), textarea, email, select, checkbox, date, time, number, passwordinputOptionsinputType을 select 또는 checkbox로 선택했을 시에 해당 format을 적어줘야 한다.

prompt options 예제

bootbox.prompt({
    title: "This is a prompt with a set of checkbox inputs!",
    inputType: 'checkbox',
    inputOptions: [
        {
            text: 'Choice One',
            value: '1',
        },
        {
            text: 'Choice Two',
            value: '2',
        },
        {
            text: 'Choice Three',
            value: '3',
        }
    ],
    callback: function (result) {
        console.log(result);
    }
});

선택에 따라서 해당 value 값이 result로 반환된다.

Custom Dialog 예제

custom dialog는 사용자 정의 다이얼로그라고 생각하면 된다. custom dialog는 옵션 객체중에 하나의 인수만 허용하고 옵션 객체의 필수 속성은 message 속성이다.

custom dialog도 여러 옵션을 사용할 수 있는데 그 부분은 공식 사이트 링크로 대체한다. Custom dialog option

기본 예제

var dialog = bootbox.dialog({
    message: '<p class="text-center">Please wait while we do something...</p>',
    closeButton: false
});
// do something in the background
dialog.modal('hide');

init 예제

실행 하기전에 초기화를 한번 해준다. init function은 Bootbox.js 에 Public function이다.

var dialog = bootbox.dialog({
    title: 'A custom dialog with init',
    message: '<p><i class="fa fa-spin fa-spinner"></i> Loading...</p>'
});
dialog.init(function(){
    setTimeout(function(){
        dialog.find('.bootbox-body').html('I was loaded after the dialog was shown!');
    }, 3000);
});

실행하면 3초뒤에 I was loaded after the dialog was shown! 메시지가 나타난다.

Button 옵션 객체를 추가해서 해당 버튼을 클릭할 때마다 실행되는 콜백함수 예제

var dialog = bootbox.dialog({
title: 'A custom dialog with buttons and callbacks',
message: "<p>This dialog has buttons. Each button has it's own callback function.</p>",
buttons: {
    cancel: {
        label: "I'm a custom cancel button!",
        className: 'btn-danger',
        callback: function(){
            alert('Custom cancel clicked');
        }
    },
    noclose: {
        label: "I'm a custom button, but I don't close the modal!",
        className: 'btn-warning',
        callback: function(){
            alert('Custom button clicked');
            return false;
            //return false를 명시해주면 버튼을 클릭해도 dialog box 화면이 꺼지지 않는다.
        }
    },
    ok: {
        label: "I'm a custom OK button!",
        className: 'btn-info',
        callback: function(){
            alert('Custom OK clicked');
        }
    }
}
});

마무리

사실 공식 홈페이지에 다 나와있는 거를 그냥 한번 정리하듯이 써 보았다. 공식 홈페이지에 가서 직접 보는게 오히려 이해가 더 빠를 것 같다.

그러나 Bootbox에 대한 포스팅이 별로 없길래 한번 작성해 보았다. 음..여러가지 틀린 점도 있을 수도 있지만 제대로 활용하려면 공식 사이트에

Documentation이 잘 되어있으니 확인하고 직접 예제를 실행해 보면서 멋진 웹 화면을 만들면 좋을 것 같다!

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함