Executing a function when a dropdown in Bootstrap is expanded and closed

How can I use JavaScript to execute a function when clicking on a notification button in a Bootstrap navbar to expand the dropdown, and then close the dropdown when clicking it again?

I have tried selecting the dropdown and modifying the click function, but it only executes when clicking an element within the dropdown, not the button itself.

#ex4 {
    color: white;
    width: auto;
}

#ex4 .p1.has-badge:after {
    position: absolute;
    right: 10%;
    top: 8%;
    content: attr(data-count);
    font-size: 40%;
    padding: .2em;
    border-radius: 50%;
    line-height: 1em;
    color: white;
    background: rgba(255, 0, 0, .85);
    text-align: center;
    min-width: 1.5em;
}

form.logout {
    padding-left: 10px;
}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

  <!-- Bootstrap Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>

  <!-- Font awesome-->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <!-- Page style -->
  <link rel="stylesheet" href="CSS/index.css">

  <!-- Title -->
  <title>Social Feed</title>
  
</head>

<body>
  <nav class="navbar navbar-dark bg-dark">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">Social Feed</a>
      <div class="d-flex align-items-center">
        <div class="dropdown">
          <a class="btn btn-secondary" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
            <div id="ex4">
              <span class="p1 fa-stack fa-2x has-badge" data-count="0" id="badge">
                <i class="p2 fa fa-bell fa-stack-1x xfa-inverse"></i>
              </span>
            </div>
          </a>
          <div class="dropdown-menu dropdown-menu-end">
            <div id="notifications-header">
              <h1>Notifications</h1>
            </div>
            <div id="notifications">

            </div>
          </div>
        </div>
        <form a name="logout" class="logout" action="PHP/Logout.php" method="get">
          <button type="submit" class="btn btn-danger">Log Out</button>
        </form>
      </div>
    </div>
  </nav>
</body>

</script>
</html>

Answer №1

Utilize the Dropdown events

var dropdownMenu = document.getElementById('dropdownMenu')

//show/open
dropdownMenu.addEventListener('show.bs.dropdown', function () {
  // perform actions when opened...
})

//hide/close
dropdownMenu.addEventListener('hide.bs.dropdown', function () {
  // perform actions when closed...
})

Codeply Example

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

Reset the text input field when the dropdown menu is set to 'no/other'

CURRENT: Choosing from a dropdown menu with options 'Yes' or 'No'. If 'Yes' is chosen: Display additional dropdowns/inputs for entry If 'No' is chosen: Conceal additional dropdowns/inputs WANT: I am looking to imp ...

Tips for executing a script while updating npm version

Can a script be executed during the npm version command, after the release number has been incremented but before the git tag is created and pushed? ...

Guide to customizing the value appearance in tooltip axispointer chart (angular)

Check out the code snippet here: https://stackblitz.com/edit/angular-ngx-echarts-zn8tzx?file=src/app/app.component.ts view image description I am looking to format and add the text "UPLOAD" and "DOWNLOAD" below the date and time. For instance: 2020-02- ...

Ways to programmatically compare all elements between two separate arrays

Is there a way to create a process where the first loop iterates through the elements of one array, while another loop goes through a second array and compares each element in the first array with all elements in the second array? For example: //first loo ...

A guide to managing Ajax in functional components in React without using classes

Currently, I am striving to develop all my components as pure functions. However, I have encountered an issue. The component I am working on resembles the structure below. The problem arises when the result of an ajax request triggers a rerender, leading ...

Obtaining the textarea value from LineControl Editor in an MVC Controller: A Step-by-Step Guide

I recently integrated a jQuery plugin into my MVC 5 project to create a wysiwyg text editor. In one of the views, I included a textarea where the text editor is meant to be displayed. However, I encountered an issue with binding or retrieving the value o ...

How to center align text in the media-body using Bootstrap 4 Beta

Struggling to vertically align the text in media-body to the middle when using the new Bootstrap 4 beta version. Tried an approach mentioned in this solution, but it didn't work with the latest version of Bootstrap. Attempted using text-center and a ...

Code for Custom Controllers in Strapi Beta version 3.0

I have encountered some discrepancies in the beta version of Strapi's controllers compared to the previous version. The new version includes multipart/sanitization boilerplate, and I am having trouble integrating my order object and Stripe charge. Be ...

What is causing the pull-right class to not function correctly in Bootstrap version 4.1.0?

After upgrading from Bootstrap version 3+ to 4.1.0, I encountered an issue with aligning elements using pull-right and pull-left, as well as float-right and float-left. The problem persists despite my efforts. Here is an image (https://i.sstatic.net/Z6ba3. ...

Utilizing AngularJS: Employing the $q Promise Feature to Await Data Readiness in this Scenario

I am currently facing an issue with my Controller and Factory. The Controller initiates an API call in the Factory, but I am struggling to make it wait for the data to be gathered before proceeding. This is where I believe implementing something like $q mi ...

The select2 jQuery plugin is malfunctioning following an AJAX request to update the HTML content

I have implemented an AJAX function to change the content of a HTML div. Within this changed content, there is a select box with the 'select2' jQuery class. However, after the AJAX load, the select2 jQuery plugin does not work properly. Here is ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

What is the best way to redirect to the index page after successfully submitting a new record on the front-end? [Using Rubymine 2020.2.3, Ruby 2.7.2p137, and gem 3.1.2]

For weeks now, I have been struggling with a college project course, unable to resolve an error despite the advice given by colleagues and tutors. In my create method for a specific table, I am facing an issue where the page should redirect back to the in ...

Require assistance resolving a CSS problem on IE8?

Greetings everyone, I am currently facing some compatibility issues with my style sheets, particularly in IE 8. The CSS code below functions perfectly in my Chrome/Firefox style sheet, but unfortunately, it does not have any effect on my IE stylesheet. # ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

What is the most efficient method for updating URLs in CSS files before the website goes live?

The project I am currently working on has been worked on by various coders with different backgrounds. One of my recent achievements was writing a clean Capistrano recipe to minimize CSS and JS files. Now, the challenge ahead is figuring out how to identif ...

Unexpected event triggering

I have come across a snippet of code that allows me to retrieve URL query strings var QueryURL = function () { var query_url = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i< ...

What is causing the dysfunction of angular2 form when used with the HTML <form> tag?

Can someone explain the strange behavior of the <form> element in ng2 to me? I have noticed something odd and need some clarification :) To demonstrate, I have created a simple Plunker example at this link: https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD ...

Divide HTML content while keeping inner tags intact

Currently, I am developing an online store. In my code, there is a requirement to display attributes and descriptions for multiple products on a single page. The attributes are displayed in a table format, while the description can include simple text as w ...

Enhancing Bootstrap UI Typeahead to Display Multiple Fields in Results List

Having encountered the same issue as described in this question: Bootstrap-UI Typeahead display more than one property in results list? I made adjustments to the Plunker provided in the answer to fit my requirements: http://plnkr.co/edit/FdkvCUUD3ob7dt2 ...