Button Onclick Show Popup Message box in Html

Admin
0
To create a button that shows a popup message in HTML, you can use JavaScript with a simple alert function or a more customized popup using a modal. Here's how to do it with both methods:

Method 1: Using alert (simple popup)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Button Popup</title>
</head>
<body>

<button onclick="showPopup()">Click Me</button>

<script>
    function showPopup() {
        alert("Hello! This is your popup message.");
    }
</script>

</body>
</html>

Method 2: Using a Modal Popup (styled popup)

This method uses CSS to style the popup as a modal and JavaScript to toggle its visibility.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Button Modal Popup</title>
    <style>
        /* Modal styles */
        .modal {
            display: none; /* Hidden by default */
            position: fixed; 
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }
        .modal-content {
            background-color: #fff;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 300px;
            text-align: center;
            border-radius: 8px;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 24px;
            cursor: pointer;
        }
    </style>
</head>
<body>

<button onclick="showModal()">Click Me</button>

<div id="myModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal()">&times;</span>
        <p>Hello! This is your popup message.</p>
    </div>
</div>

<script>
    function showModal() {
        document.getElementById("myModal").style.display = "block";
    }

    function closeModal() {
        document.getElementById("myModal").style.display = "none";
    }

    // Close modal when clicking outside
    window.onclick = function(event) {
        let modal = document.getElementById("myModal");
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>

</body>
</html>

The first method provides a quick solution, while the second one gives you more control over the popup's style and appearance. Let me know if you need further customization!


Tags

Post a Comment

0 Comments
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Ok, Go it!