The Bootstrap alert refuses to close when the close button is clicked

I'm attempting to utilize a Bootstrap alert for displaying a warning. The alert automatically fades and dismisses after a period of time, but I want to provide the user with the option to manually close it. I've included jQuery and js/bootstrap.min.js in the recommended order based on responses to similar inquiries.

Here is my HTML code:

<div class="alert alert-warning alert-dismissible errormessage" role="alert"
style="display: none;">
    <button type="button" class="close" data-dismiss="alert"
    ng-click="dismissError()">
            <span aria-hidden="true">&times;</span>
            <span class="sr-only">Close</span>
    </button>
    {{ errormessage }}
</div>

And this is my JavaScript:

//sets errormessage to be displayed
function displayError(error) {
    if(error){
            $scope.errormessage = error;
            $('.errormessage').fadeIn(300).delay(5000).fadeOut(500);
    }

$scope.dismissError = function() {
    $scope.errormessage = '';
    $('.errormessage').hide();
};

CSS:

.errormessage{
    position: fixed;
    top: 1%;
    left: 50%;
    margin-left: -250px;
    width: 500px;
    padding-top: 5px;
    padding-bottom: 5px;
    z-index: 9999;
    text-align: center;
}

The default close functionality doesn't seem to be working, so I also attempted to implement the dismissError function to manually close the alert, but upon debugging, it appears that the code doesn't enter my function.

NOTE: I've already tried:

<button type="button" class="close" data-dismiss="alert"
aria-hidden="true">&times;
</button>

and

<button type="button" class="close" data-dismiss="alert"
onclick="$('.alert').hide()" aria-hidden="true">&times;
</button>

both of which had no effect. I also attempted changing the z-index to 2, but still couldn't close the alert. Thank you for all the assistance!

PS: I'm implementing this within a Chrome app that I'm developing

Answer №1

If you're utilizing AngularJs in tandem with Bootstrap, have you considered integrating Angular UI for Bootstrap?

To implement this, simply include a ui-bootstrap-min.js file in your scripts and create a controller for the alert, like so:

<div class="alert alert-warning alert-dismissible errormessage" role="alert" style="display: none;" ng-controller="AlertCtrl">  
         <alert type="{{alert.type}}" close="closeAlert()">{{ errormessage }}</alert>  
</div>

For the corresponding Javascript code:

angular.module('ui.bootstrap.demo').controller('AlertCtrl', function ($scope) {  
    $scope.alert = [  
        { type: 'danger', errormessage: 'Your own error message' }, 
    ];  

    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };
 });

While this may not be the ideal Javascript solution, it serves as a foundation for further development.

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

The functionality of jQuery click events seems to be disabled on the webpage, however, it is working perfectly fine on jsFiddle

After thoroughly checking the js tags and ensuring everything is properly closed, it's frustrating when the JavaScript suddenly stops working. The code functions perfectly in JSFiddle, leading me to believe that the issue may lie with something I&apos ...

When using React, the page loads and triggers all onClick events simultaneously, but when clicking on a button, no action is taken

I have a strong foundation in HTML and CSS/SASS but I'm just getting started with React. Recently, I encountered an issue that has me stumped. I am trying to highlight a button on the navigation bar based on the current page the user is on. I attemp ...

The custom server was functioning properly, but as soon as I altered the file directory, an error occurred on Next.js

After creating "create-next-app," I successfully set up the folder structure as follows: +client2 --.next --node_modules --public --... --server.js However, when I move my "server.js" file to a different location: +client2 --.next --no ...

"Switching a div's visibility when a link is clicked

http://jsfiddle.net/FsCHJ/2/ Currently, when I add another link, it automatically uses the same functionality as the toggle button. What I want is for "Toggle Edit Mode" to toggle a hidden div on and off. I attempted to modify the code from $("a").click(f ...

Sharing state between two functions in React using Hooks

Coming from a background in Vue, I am struggling to comprehend how to conditionally show something when the HTML is fragmented into different parts. Imagine having this structure: import React, { useState } from "react"; const [mobileNavOpen, setMobi ...

Transmitting the character symbol '&' within a string from Angular to PHP

My goal is to transmit a string, such as "the cat & the dog", from Angular to PHP using GET method. I have used encodeURI(note) in Angular and in PHP $note = $_GET['note']; $note = mysql_real_escape_string($note); However, when it gets inse ...

Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code ...

Can we break down and explain iterative dynamic imports with conditions in JavaScript?

Is there a way to simplify the named imports and assignments in my code programmatically without repeating myself? I am looking for a solution that involves using a loop. This is what I currently have: import { globalLocale } from './i18n' let ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

Limit the outcomes of the Ionic timepicker

Currently, I am utilizing the ionic datetime feature. However, instead of receiving just the hours, minutes, and seconds, the result I am getting looks like this 2020-10-05T00:00:27.634+07:00. What I actually require from this output is only 00:00:27. Is ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...

The authentication method "discord" is not recognized

Currently, I am working on implementing discord authentication using passport. Originally, everything was functioning correctly, but now it seems to have encountered an issue which I cannot identify. auth.js const express = require('express') co ...

The result from the AngularJs promise is coming back as undefined

I am facing an issue while trying to implement the login function of my AuthService factory in conjunction with my AuthLoginController controller. The problem arises when the User.login function is triggered with incorrect email and password details, causi ...

Tips for managing a 64-bit signed integer received from a NextJS backend API

I am currently developing a NextJS application in which one of the backend API routes sends back a JSON object that includes a 64-bit signed integer. // userID represents the 64-bit signed integer res.status(200).json({ id: userId, attributes: userAttribut ...

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 ...

Utilizing jsPDF and html2canvas in a Vue.js application (no webpack involved)

I've been working on a feature within a Vuejs project that allows users to export a PDF containing specific Vuejs components by clicking a button. Everything was going smoothly until I encountered an issue. After npm installing the jsPDF and html2canv ...

Is There a Way to Abandon a route and Exit in Express during a single request?

In order to ensure proper access control for the application I was developing, I structured my routing system to cascade down based on user permissions. While this approach made sense from a logical standpoint, I encountered difficulties in implementing it ...

What is the best way to determine if certain rows of data have been successfully loaded when working with Ext.data.operation and an ajaxProxy?

Here is the provided code snippet: Ext.define('Book', { extend: 'Ext.data.Model', fields: [ {name: 'id', type: 'int'}, {name: 'title', type: 'string'}, {name: &apo ...

Choose a Different Value for Another HTML Element's Class

Is there a way to preselect an option on another page before it loads? Consider two pages, A and B. If a user clicks a button on page A, I want the default option on page B to be changed to "something" before redirecting them. How can this be achieved s ...

Catching the Selenium NoSuchElementError in JavaScript is impossible

Update: It's puzzling why this was marked as answered since the linked questions don't address the issue at hand and do not involve Javascript. My objective is to detect this error, rather than prevent it, given that methods like invisibilityOfEl ...