How to use display property to create custom alert In Javascript

This method involves crafting a custom alert-like dialog using HTML, CSS, and JavaScript. By constructing the dialog from scratch, developers gain complete control over its appearance, including its color.

Example: The below code example will explain how you can create your custom alert dialog.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Custom Alert Box</title>
    <link rel="stylesheet" href="style.css">
</head>

<body style="text-align: center;">

    <h2>
        Creating a custom alert box
    </h2>
    <button class="open-btn" onclick="showAlert()">
        Show Alert
    </button>

    <div id="customAlert" class="custom-alert">
        <span class="close-btn" onclick="closeAlert()">
            &times;
        </span>
        <p>This is a custom alert!</p>
    </div>

    <script>
        function showAlert() {
            const alertBox = 
                document.getElementById('customAlert');
            alertBox.style.display = 'block';
        }

        function closeAlert() {
            const alertBox = 
                document.getElementById('customAlert');
            alertBox.style.display = 'none';
        }
    </script>

</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
}

.custom-alert {
    display: none;
    position: fixed;
    top: 20%;
    left: 50%;
    transform: translate(-50%, -20%);
    background-color: #4CAF50;
    padding: 30px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.custom-alert p {
    margin: 0;
    color: #ffffff;
}

.open-btn{
    color: #fff;
    background: green;
    border: none;
    padding: 10px;
    border-radius: 8px;
    cursor: pointer;
}

.close-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    cursor: pointer;
    font-size: 20px;
    color: #ffffff;
}

Output:

How to Change the Color of the Alert Box in JavaScript ?

Alert boxes, often utilized in JavaScript applications, provide users with important notifications or messages. However, their default appearance may not always blend seamlessly with the overall design of your website or application.

JavaScript offers several methods to customize alert boxes as listed below.

Table of Content

  • Using display property to create custom alert
  • Using visibility property to create custom alert

Similar Reads

Using display property to create custom alert

This method involves crafting a custom alert-like dialog using HTML, CSS, and JavaScript. By constructing the dialog from scratch, developers gain complete control over its appearance, including its color....

Using visibility property to create custom alert

We can use the visibility property in the same way as we used the display property to hide and show the alert box on click to the button....