Custom Alert Box in Javascript
In this tutorial, you will learn how to create a custom alert box in javascript. If we use an alert() method in javascript the appearance is not good. So we need to create a custom alert box for users attractive and responsive. And if we do some animation in the alert box it will be good for the user experience. Everyone uses custom alert boxes and many don’t use the default alert box.
Step-by-step guide to creating an alert box
- 1. Copy the below <script> code and paste it in your <head> tag.
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"> </script>
- 2. Go to the Sweetalert2 website and select your alert box theme.
- 3. Click the “try me” button and watch the preview. Copy the code of the selected alert box and create a function in your HTML <script> tag then paste it.
- 4. Then Create a button using the <button> tag in the body. And add “onclick” attribute and give the function name as a value.
- 5. Now, see the output once you click the button the custom alert box will display.
Example code
<!DOCTYPE html>
<html>
<head>
<title>Horizontal line width</title>
<!-- Step 1: paste the Sweetalert2 code -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<!--Step 3: create button with onclick -->
<button onclick="display()"> Onclick </button>
</body>
<script type="text/javascript">
// Step 2:Create a function and paste the alert box code inside it
function display(){
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
}) }
</script>
</html>
- In the above code, we have paste the Sweetalert2 <script> code in the <head> section.
- Then we create a function and paste the Sweetalert2 custom alert box code inside it.
- And, we create a button using <button> tag. Then we add an “onclick” attribute and give the JS function name as a value.
- If you want to edit the title of the alert box, you can change the “title” field in the above code. Similarly, you can edit text, icons, and button colors.
- If you want to change the icon for your alert box, you need to edit the ‘value’ in the “Icon” field. See the image below and give the icon name you want.