Open In App

How to Edit a JavaScript Alert Box Title ?

We can't directly modify the title of the alert box because the title is controlled by the browser and cannot be changed by JavaScript. However, we can create a custom alert box.

Using a Custom Alert Box Function

In this approach, we are creating a function that dynamically generates an alert box with a customizable title and message. This approach allows us to have more control over the appearance and behavior of the alert box compared to the standard alert() function in JavaScript.

Example: The below example creates custom function to edit a JavaScript alert box title.

<!DOCTYPE html>
<html>

<head>
  <title>Custom Alert Box</title>
  <style>
    .container{
        text-align: center;
    }
    h1{
        color: green;
    }
    .custom-alert {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #fff;
      border: 1px solid #ccc;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }
  </style>
</head>
<body>
    <div class="container">
        <h1>GeeksForGeeks</h1>
        <h3>Using custom function</h3>
        <button onclick=
            "showAlert('Custom Alert', 'This is a custom alert box.')">
                Show Alert
        </button>


    </div>


<script>
  function showAlert(title, message) {
    // Create a custom alert box
    const alertBox = document.createElement('div');
    alertBox.className = 'custom-alert';
    alertBox.innerHTML = `
      <h2>${title}</h2>
      <p>${message}</p>
      <button onclick="document.body.removeChild(this.parentElement)">OK</button>
    `;
    document.body.appendChild(alertBox);
  }
</script>

</body>
</html>

Output:

calert

Using SweetAlert Library

In this approach we are using SweetAlert library which allows us to create custom-styled alert boxes with ease. It provides a simple and elegant way to display alerts, prompts with customizable titles, messages, and buttons.

Example: The below example uses SweetAlert Library to add custom title in alert box.

<!DOCTYPE html>
<html>

<head>
    <title>Custom Alert Box</title>
    <script src=
"https://cdn.jsdelivr.net/npm/sweetalert2@11">
      </script>
</head>
<style>
    .container {
        text-align: center;
    }

    h1 {
        color: green;
    }
</style>

<body>
    <div class="container">
        <h1>GeeksForGeeks</h1>
        <h3>Using SweetAlert library</h3>
        <button onclick="showCustomAlert()">
              Show Alert
          </button>

    </div>


    <script>
        function showCustomAlert() {
            // Create a custom alert box with SweetAlert
            Swal.fire({
                title: 'This is a Custom Alert title',
                text: 'Welcome to geeksForGeeks',
                confirmButtonText: 'OK'
            });
        }
    </script>

</body>

</html>

Output:

sweet

Article Tags :