`Close a bootstrap alert by clicking anywhere outside of it`

Bootstrap Warnings Image Two types of bootstrap alerts are present - warning and danger. Danger alerts always remain on the page, while warning alerts pop up when the user clicks on the dropdown list for carriers, displaying a notification. The user can close it by clicking on 'x'. However, I need it to also close when the user clicks anywhere on the page or on the 'x'.

HomeController.cs

case "Carrier":
    var carrierid = (from foo in db.Carriers
                     where foo.ID == warningid
                     select foo.WarningID).Single();
    if (carrierid != null)
    {
        warning = (from warnings in db.Warnings
                   where warnings.IsActive == true && warnings.Id == carrierid
                   select warnings.WarningBody).SingleOrDefault();
        if (warning != null)
        {
            warning = ("<div class=\"alert alert-warning alert-dismissible\" id=\"myWarning\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button><strong>" +
            warning + "</strong></div>");
        }
        else
        {
            warning = "";
        }
    }
    else
    {
        warning = "";
    }
    return Json(warning, JsonRequestBehavior.AllowGet);
default:
    break;

warningwriter.js

           //// warning display script takes a value of warningid and warningcaller
            $(document).ready(function () {
                   var warningid = 0;
                   var warningcaller = "Universal";
                   loadWarnings(warningid, warningcaller);
             });
              $('#Phones').change(function () {
                   var warningid = $(this).val();
                   var warningcaller = "Phone";
                   loadWarnings(warningid, warningcaller);})
             $('#Carriers').change(function () {
                   var warningid = $(this).val();
                   var warningcaller = "Carrier";
                   loadWarnings(warningid, warningcaller);})
          function loadWarnings(warningid, warningcaller) {
$.getJSON("../Home/LoadWarnings", { warningID: warningid, warningCaller: warningcaller },
            function (warning) {
            var select = $('#warnings');
            select.append(warning);

    });    
}; 

Answer №1

Following Martin's advice, the solution involves incorporating javascript code. Although not personally verified, the script would resemble the following:

$(document).click(function (event) {            
   $(".alert").hide();
});

Essentially, clicking anywhere on the webpage will result in any shown alerts being hidden.

Answer №2

When it comes to handling different types of bootstraps alerts, such as danger and warning, it is important to use the appropriate classes for each. In this case, ".alert-warning" should be used if you want to remove the alert when a user clicks anywhere on the page. The class ".alert" encompasses all bootstraps alerts, but using contextual classes like .alert-success, .alert-info, .alert-warning, and/or .alert-danger allows you to target specific types. For more information, visit

$(document).click(function (event) {
   $(".alert-warning").hide();
});

Answer №3

$(document).ready(function () { 
     $("#myWarning").click(function () {  
         $(".alert").alert("close"); 
     }); 
 });

When implementing this code, there are a couple of things to consider:

  1. You are attaching the click event to an element that may not exist when the page loads initially.
  2. Your click event is limited to only working on a specific element (in this case #myWarning), meaning the alert will not close if you click anywhere else on the page.

It would be better to follow the suggestion by @Bryan for a more robust solution :)

Edit:

If you have a group of alerts that should automatically close on page load, add a common identifier such as a "close-on-screenclick" class to these elements.

$(document).click(function () { 
     $(".close-on-screenclick.alert").alert("close");  
 });

This modification will ensure that these elements are closed whenever a click occurs anywhere on the screen.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Image carousel with interactive buttons

I've taken over management of my company's website, which was initially created by someone else at a cost of $24,000. We recently made some edits to the slideshow feature on the site, adding buttons that allow users to navigate to corresponding p ...

Application becomes unresponsive following database write caused by an infinite loop

I have a user_dict object that is generated by fetching data from a Firebase database. Once the user_dict object is created, I store a copy of it within a profile child under the uid. Although the necessary information is successfully saved to the databas ...

Automatically refresh the Redux state in ReactJS at regular intervals to ensure the data is always up-to

I'm trying to implement a solution for running a background process in my React App, which will periodically call a backend API and update the redux state. The app is quite large with numerous components, so I need a global approach that doesn't ...

Stop a div at a specific point with this unique jQuery plugin

I am looking to implement a similar feature on my website that can be seen here: The desired functionality is when a link stops at a certain point while scrolling, and upon clicking the link it smoothly scrolls to a designated div. Additionally, as you sc ...

Guide to effectively invoking JavaScript functions using jQuery

<head> <script src="jquery-latest.js" /> <script> function resetValues(){ alert('Inside the resetValues function'); //using hexadecimal routine 1 -> 3 -> 5 -> 8 -> (11 == a) document.getElementB ...

Creating a dynamic map in AngularJS by parsing and utilizing data from a JSON file

Looking to create a map from JSON data returned by a RESTFUL WEB Service using AngularJS. Here is an example of the JSON format: myJSON = [{ id: 8, color: "red", value: "#f00" }, { id: 37, color: "green", value: "#0f0" }, { id ...

The optimal times and situations for implementing the FindElement method from the By class

My understanding of Selenium architecture includes the concept of Search Context as the main interface implemented by the Web Driver interface, which is then extended by various browser driver classes. In our selenium projects, we typically follow the Page ...

I am currently working on creating a system for displaying rating stars for products. The rating value, which ranges from 0 to 5, has already been provided

class PostBodyRatingStars extends React.Component { render() { const { classes } = this.props var rating = this.props.rating function createMappingArray(rating) { var arr = [] for (i = 0; i < 5; i++) { if (rating >= ...

A step-by-step guide on utilizing the reduce function to calculate the overall count of a user's GitHub repositories

I need help finding the total number of repositories for a specific user. Take a look at my code below: Javascript const url = "https://api.github.com/users/oyerohabib/repos?per_page=50"; const fetchRepos = async () => { response = await f ...

`You may encounter a error message indicating "ReferenceError: <package> not defined" even after successfully installing the package.`

After successfully running the command npm install chevrotain in a specific folder, I checked the version with npm -v chevrotain, leading me to get 8.1.2. In my package.json file, I have "chevrotain": "^10.1.2" listed under dependencies ...

Display or conceal a field depending on the user's input

I need to display a checkbox only when the firstname matches abc or if the email is [email protected]. var x = abc; //will be dynamic var y = abc @gmail.com jQuery("#firstname").on('change', (function(avalue) { return function(e) { ...

Retrieve and showcase the Child ID associated with the Parent ID

In my HTML code, I have a parent div with the ID "parentID", and I dynamically assign the ID "ChildID" to all its child divs along with the parent's ID. jQuery(document).on('click', '.split-id', function() { var parentID = jQu ...

React | The virtual DOM modal refuses to display

I'm currently utilizing React JS in tandem with Ant Design for my latest project. Issue My virtual DOM element features a Popover which contains a Button that, once clicked, displays a Modal. An error is being triggered: Cannot read property ' ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

The expiration and creation of access tokens in the Gmail API

For the past 6 months, I have been utilizing the Google API to send emails from my server in a Node.js project. I have successfully set up credentials and generated both refresh and access tokens, which I have been using consistently. oAuth2Client = new go ...

submitting numerous forms using AJAX

On my webpage, each entry in the database has its own form that saves data upon pressing the enter key. However, I am facing an issue where only one specific form is being saved and not all of them. How can I differentiate between the forms and ensure that ...

What is the significance of having multiple route parameters in Express?

The RESTful API provided by cex.io offers a route that can return pairs of all currencies with a variable amount of parameters. In express, how can we achieve similar functionality? Consider the following pseudo code example... app.get('/pairs/:arg ...

Adding a C# variable to a URL in a Razor view using jQuery

My Razor page looks like this: @{ ViewData["Title"] = "mypage"; string ApiAddress = "https://localhost:8114/api/"; } <div> ... </div> @section Scripts{ <script> functio ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

"Implementing dynamic loading of an angularjs controller directly from an HTML

I have 2 controllers. I receive a composite JS object containing elements, JS objects, and multiple arrays from the first controller My goal is to initialize the second controller multiple times with different array objects. This is how I am initializing ...