Bootsrap alert auto close example
May 23, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To make an alert auto close, put the setTimeout()
method to close the alert after a specified time. it will show the alert auto close on a page.
In this tutorial, learn how to create a bootstrap alert auto close example.
All modern web application uses alerts
to show messages to the user. These alerts
have a close button to close them or can be closed automatically using Twitter Bootstrap. In this post, we will create automatically closing of alerts
using twitter Bootstrap.
Table of contents
- Includes bootstrap library
- Include the code in body
- Add JavaScript in
<script>
tag
Syntax:
setTimeout(function, delay)
Note: Delay is defined in milliseconds. 1 second is equal to 1000 milliseconds.
Step 1: Includes bootstrap library
First of all, load the Bootstrap framework CSS into the head tag of your webpage.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- Including jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
</script>
<!-- Including Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">
</script>
Step 2: Include the code in body
Include the code below in <body>
to accept time from the user.
<div id="alert" class="alert alert-danger">
This alert will automatically
close in 5 seconds.
</div>
Step 3: Add JavaScript in <script>
tag
Add the following JavaScript in <script>
tag after the <body>
tag to specify alert auto close.
<script type="text/javascript">
setTimeout(function () {
// Closing the alert
$('#alert').alert('close');
}, 5000);
</script>
Example.
Let’s look at the following example to understand how it basically works:
<!DOCTYPE html>
<html>
<head>
<title> Bootstrap </title>
<!-- Including Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- Including jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
</script>
<!-- Including Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">
</script>
</head>
<body>
<h3>Auto close the alert</h3>
<!-- Showing alert -->
<div id="alert" class="alert alert-danger">
This alert will automatically
close in 5 seconds.
</div>
<script type="text/javascript">
setTimeout(function () {
// Closing the alert
$('#alert').alert('close');
}, 5000);
</script>
</body>
</html>
Check the output of the above code example.
In this example, alert is accessed in script using the id and then alert is closed after 5 seconds.
All the best 👍