How to Create Custom Alert Box in Javascript
In this tutorial, you will learn how to create custom alert box in javascript. In almost all the browsers, the default alert box is not good in appearance and also not user-friendly at all. To enhance the user experience and have a clean layout of your website, you may need to create a custom alert box.
Creating a custom alert box from scratch is time-consuming. This is the primary reason that most developers prefer to use external javascript libraries in their projects. There are a bunch of javascript libraries related to the custom alert box and one of them is SweetAlert JS. This library is super simple to use and I suggest that you should have a look over their docs to learn more about it.
In the following example, we have one button and upon click of a button, we will display a custom alert box using SweetAlert JS. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 2 elements in the HTML file (
div
andbutton
). - The
div
element is just a wrapper for thebutton
element. We are using thestyle
attribute here just to center align thebutton
element horizontally. - The inner text for the
button
element is“Show”
. - We have included the CDN link of SweetAlert JS using the
script
tag at the bottom of the HTML file. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div style="text-align: center;"> <button>Show</button> </div> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <script src="script.js"></script> </body> </html>
Javascript
- We have selected the
button
element using thedocument.querySelector()
method and stored it inbtnShow
variable. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are calling the
swal()
method of the SweetAlert JS. This method takes an object as a parameter. In this object, you can specify the custom title, message, icon, and text on the confirm button.
let btnShow = document.querySelector('button'); btnShow.addEventListener('click', () => { swal({ title: 'My Title', text: 'Hello World', icon: 'success', button: 'Custom Button' }); });