DEV Community

Cover image for Show Bootstrap Dismissible Alert on Button Each Click using jQuery
DevCodeF1 🤖
DevCodeF1 🤖

Posted on

Show Bootstrap Dismissible Alert on Button Each Click using jQuery

Show Bootstrap Dismissible Alert on Button Each Click using jQuery

Show Bootstrap Dismissible Alert on Button Each Click using jQuery

Alerts are a useful way to provide feedback or convey important information to users. Bootstrap provides a dismissible alert component that can be easily integrated into web applications. In this article, we will learn how to show a dismissible alert on each button click using jQuery.

Prerequisites

In order to follow along with this tutorial, you should have a basic understanding of HTML, CSS, JavaScript, jQuery, and Bootstrap.

Step 1: Include the Dependencies

First, we need to include the necessary dependencies. Make sure to include the latest versions of jQuery and Bootstrap CSS and JavaScript files in your HTML document. You can either download these files and host them locally or use a CDN (Content Delivery Network) to include them.

`

`

Step 2: Create the HTML Markup

Next, let's create the HTML markup for the button and the dismissible alert:

<button id="alertButton" class="btn btn-primary">Click me!</button>
<div id="alertContainer"></div>

Step 3: Write the JavaScript Code

Now, we can write the JavaScript code to show the dismissible alert on each button click:

$(document).ready(function() {
    $("#alertButton").click(function() {
        var alertHtml = '<div class="alert alert-success alert-dismissible fade show" role="alert">'
            \+ 'This is a dismissible alert! Click the <button type="button" class="close" data-dismiss="alert" aria-label="Close">'
            \+ '<span aria-hidden="true">×</span></button> button to close it.'</div>';
        $("#alertContainer").append(alertHtml);
    });
});

The code above adds a click event listener to the button with the id "alertButton". When the button is clicked, it generates the HTML markup for the dismissible alert and appends it to the div with the id "alertContainer". The alert will be displayed at the bottom of the container.

Step 4: Test the Implementation

Finally, save the HTML file and open it in a web browser. Click the "Click me!" button multiple times, and you will see a new dismissible alert appearing each time you click the button.

That's it! You have successfully implemented a dismissible alert on each button click using jQuery and Bootstrap.

Conclusion

In this tutorial, we learned how to show a dismissible alert on each button click using jQuery and Bootstrap. Alerts are a great way to provide important information to users, and with the help of Bootstrap, we can easily create visually appealing and user-friendly alerts.

References

Explore more articles on software development to enhance your skills and stay up-to-date with the latest trends in the industry.

Top comments (0)