Utilizing the Bootstrap alert function without any arguments

https://getbootstrap.com/docs/4.0/components/alerts/

Exploring the world of Bootstrap 4.0, I came across an interesting method in the documentation:

$('.alert').alert()

This method allows an alert to listen for click events on its descendant elements that have the data-dismiss="alert" attribute. (This is not required when using the data-api’s auto-initialization.)

In order to test this method, I decided to try some code snippets:

$(document).off('.alert.data-api'); // executed successfully
$('.alert').alert(); // seemingly does nothing

<div id='mydiv' class="alert alert-warning alert-dismissible fade show" role="alert">
text
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
</button>
</div>

Surprisingly, the alert() method appears to be ineffective in making the button work as expected. This raises the question: why is it not functioning correctly?

Answer №1

It seems there might be some confusion regarding the proper usage of $(selector).alert(). When you call the alert function without any parameters, what it actually does is instruct Bootstrap to listen for clicks on child elements that contain data-dismiss="alert" - refer to the example provided below.

In the code snippet you shared, 'myDiv' is not closed, causing your code to malfunction as the close button is not placed within the alert div.

$(function() {
  $('#alertDiv').alert()
})
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">


<div id='alertDiv' class="alert alert-warning alert-dismissible fade show" role="alert">
  Alert Message!
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

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 combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

How can I extract an array of objects from a response in Angular?

Arrange array of objects from the received data. Here is the data that I received. [ {name:someName, value:20}, {name:"", value:21} {name:someName, value:25} {name:someName , value:27} {name:"", value:21} {name:someName, value:20} ] I am looki ...

React: Component styles fail to update dynamically

I have been working on creating a component that can adjust its size dynamically based on props. Currently, I am experimenting with the code below, but I've noticed that when I change the slider, the component's size doesn't actually change. ...

Chrome is experiencing a delay in closing the Select Option dropdown menu

On my webpage, I have two select option buttons placed on different tabs. Whenever one button is changed, I want to update the value of the other button and assign it to a specific element like a span in the example code provided. While everything works sm ...

Utilize NodeJS to dynamically alter the text outputted on an HTML page

For educational purposes, I am designing a website where users can sign in by entering their name on the login page. After signing in, they will be redirected to the home page which displays a personalized welcome message using their name. I have included ...

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

Having trouble with the "Corrupted @import" error during grunt build?

As I embark on my journey to create my very first Angular application, I have encountered a roadblock. Using Yeoman and angular-generator, everything seemed to be running smoothly with "grunt serve." However, when I attempted to execute "grunt build," the ...

Issue with rendering SVG <g> element in Backbone view

I'm currently developing an application with Backbone and running into issues with a view where the "el" property is a dynamically created <g> element. Here's the code snippet for the view: var DependencyLineView = Backbone.View.extend({ ...

I am aiming to display the information received from my socket event in an ajax datatable

Utilizing socket to receive JSON data from the backend, I have the DATA variable containing the information I want to iterate into the AJAX data table. Below is the code snippet I am using: ` socket.on('getinvoices', (data) => { ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...

What is the best way to save a token value to a JavaScript file on my local storage

Hello, I am new to Nodejs and have implemented passportjs token-based authentication. When a user logs in, a token is provided for each user. Now, I want to perform certain operations based on the users who have token values. For example, if a user wants t ...

"Unlocking the Power of mediaElementjs: Easy Steps to Accessing the Player Instance

I'm facing a small issue with the MediaElement.js player. To access the player instance, I usually use the following code (which works in HTML5 compatible browsers): // Retrieve player this.playerId = $('div#shotlist-player video').att ...

Switching the hierarchy of list items in React

I have a JSON structure with nested elements. const JSON_TREE = { name: "PARENT_3", id: "218", parent: { name: "PARENT_2", id: "217", parent: { name: "PARENT_1", i ...

How can I retrieve the PHP response once a successful upload has occurred using DropzoneJS?

I am currently in the process of integrating Dropzone into my website. My goal is to capture the "success" event and extract specific information from the server response to add to a form on the same page as the DropZone once the upload is finished. The k ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Using the Nodejs Array prototype filter method within a JSON object

Attempting to create a function that filters and returns specific strings within JSON data. Any advice is appreciated. Thank you! [ { line: '{"status":"waiting"}' } ] var body_W = []; body_W.push({line: JSON.stringif ...

Direct users from one path to another in Express framework

I have two main routes set up in nodejs. First is the users.js route: router.post('/users/login', function(request, response) { // Logic for user login // Redirect to dashboard in dashboard.js file after login response.redirect(&ap ...

The chosen index in the Material Stepper feature is experiencing a malfunction

I've been busy working on a Mat-Stepper, actually two of them. I have a component that contains two ng-templates set up like this: Question: Why is my selected index not functioning as expected? Am I missing something? I know you can define [selected ...

Having trouble retrieving the HTML content after deploying my application on Heroku

I encountered an issue with my index.js file in Express Node.js once I deployed the app on Heroku. In production, I'm getting an error that seems to indicate that the server is unable to find my index.html file. *-src ---index.html ---index.js http ...