How to use a Custom Alert Box Function In Javascript
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>w3wiki</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:
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.
Table of Content
- Using a Custom Alert Box Function
- Using SweetAlert Library
Contact Us