본문 바로가기
HTML/CSS

[HTML/CSS] Bootstrap의 Toast 기능 사용하기

by teamnova 2024. 4. 8.

안녕하세요.

이번 시간에는 Bootstrap에 있는 토스트(Toast) 기능을 사용해보겠습니다.

 

1. 토스트(Toast) 기능이란?

토스트(Toast) 기능은 사용자에게 메시지나 알림을 간단하게 표시하는 기능입니다.

일반적으로 페이지의 상단이나 하단에서 작은 팝업 창으로 나타나며, 일시적인 정보나 알림을 표시하는 데 사용됩니다.

 

 

2. Bootstrap 불러오기

이 예제에서는 CDN으로 Bootstrap을 불러오겠습니다.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

 

 

3. 전체 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bootstrap Test</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="padding: 20px; text-align: center;">
    <button type="button" class="btn btn-primary" id="liveToastBtn">토스트 보여주기</button>

    <div class="toast-container position-fixed bottom-0 end-0 p-3">
        <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <img src="image/logo_tstory.png" style="width: 15px;" class="rounded me-2" alt="...">
                <strong class="me-auto">Bootstrap</strong>
                <small>시간 정보</small>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body">
                안녕하세요. 토스트 메시지.
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const toastTrigger = document.getElementById('liveToastBtn');
        const toastLiveExample = document.getElementById('liveToast');

        if (toastTrigger) {
            const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample);
            toastTrigger.addEventListener('click', () => {
                toastBootstrap.show();
            })
        }
    </script>
</body>
</html>

 

 

4. 실행 결과