How to Create Custom Alert Box in Javascript | Easy Method

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. 1. Copy the below <script> code and paste it in your <head> tag.
    <script src="">
  2. 2. Go to the Sweetalert2 website and select your alert box theme.
  3. 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.custom alert box in javascript
  4. 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. 5. Now, see the output once you click the button the custom alert box will display.

Example code

<!DOCTYPE html>
<title>Horizontal line width</title>
<!-- Step 1: paste the Sweetalert2 code -->
<script src=""></script>


<!--Step 3: create button with onclick -->
<button onclick="display()"> Onclick </button>

<script type="text/javascript">

// Step 2:Create a function and paste the alert box code inside it
function display(){{
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) {
'Your file has been deleted.',
}) }


custom alert box in javascript

  1. In the above code, we have paste the Sweetalert2 <script> code in the <head> section.
  2. Then we create a function and paste the Sweetalert2 custom alert box code inside it.
  3. And, we create a button using <button> tag. Then we add an “onclick” attribute and give the JS function name as a value.
  4. 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.
  5. 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.custom alert box in javascript

Leave a Reply