Bootstrap version 4.1 introduces a new feature that allows the collapse menu to automatically close when clicking outside of the div

I'm currently working on creating a plug and play Mega-Menu using the collapse method which has proven to be quite effective so far.

However, I'm facing an issue with closing the collapsed item when clicking outside the menu. As a beginner in Javascript, utilizing jQuery for this task is a bit challenging for me.

Edit: I recently came across a more streamlined code that doesn't involve a mix of JavaScript and JQuery. Although I attempted to implement it, I'm still struggling to correctly target the .collapse() method.

The widget displayed below seems to have some other unrelated issues affecting its information display, similar to previous problems I've encountered. You can test out the code on this JSfiddle link.

JQuery (Edited):

$(document).mouseup(function(e) {
  var container = $("#mega-menu");

  // if the click event target isn't the container or one of its descendants
  if (!container.is(e.target) && container.has(e.target).length === 0) {
    container.collapse();
  }

Code:

.dropdown-mega-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  width: 100%;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-direction: column;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border: 1px solid rgba(0, 0, 0, .125);
  padding: 1rem;
  border-radius: 0;
}

.mega-menu-toggle {
  cursor: pointer;
}

.mega-menu-toggle::after {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: .255em;
  vertical-align: .255em;
  content: "";
  border-top: .3em solid;
  border-right: .3em solid transparent;
  border-bottom: 0;
  border-left: .3em solid transparent;
}

@media (max-width: 767px) {
  .dropdown-mega-menu {
    position: static;
  }
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<!-- Navigation -->
<nav class="navbar navbar-light bg-light navbar-expand-md sticky-top">
  <div class="container">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
  </button>
    <div class="collapse multi-collapse navbar-collapse" id="navbarNavDropdown">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link mega-menu-toggle" data-toggle="collapse" data-target="#mega-menu" role="button" aria-expanded="false" aria-controls="mega-menu">Dropdown link</a>
          <div class="dropdown-mega-menu collapse multi-collapse" id="mega-menu">
            <h3>Heading</h3>
            <div class="row">
              <div class="col-md">
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Action</a>
              </div>
              <div class="col-md">
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Another action</a>
              </div>
              <div class="col-md">
                <div>
                  Other none linked content.
                </div>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</nav>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>

Answer №1

After conducting a thorough investigation, it appears that my incorrect use of the collapse method was causing the issue. By utilizing the existing JQuery and incorporating collapse('hide'), I was able to resolve the problem:

$(document).mouseup(function(e) 
{
    var container = $("#mega-menu");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.collapse('hide');
    }
});  

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

Rendering the page using ReactDOM.render

Just started with ReactJS, I'm struggling to figure out why my page isn't displaying anything - <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ...

Parameterized Azure Cosmos DB Stored Procedure

I am currently learning about Azure Cosmos Db, and I am in the process of developing a simple JavaScript stored procedure that will return a document if a specific Id is provided. However, when I run the stored procedure, I do not receive a "no docs foun ...

Twice Triggered: Firebase Cloud Function HTTPS Call

I have thoroughly reviewed the Firebase Cloud Functions reference, guides, and sample code in an attempt to solve the issue of my function being triggered twice, but so far, I have not found a solution. I also experimented with Firebase-Queue as a workarou ...

Tips for excluding files in a webpack configuration for a Vue application during the production build

I am attempting to remove an Html file named "dev.html" from the final product build. What configurations do I need to make in webpack for this? I understand that rules need to be applied, but where exactly do I need to configure them? Below is a snippe ...

TinyMCE spelling checker request could not be completed due to a 404 error

I have tried various methods to find a solution to this problem, but unfortunately, none of them have worked. I have gone through multiple questions on this platform in search of a solution, but have not been successful. Although I am aware that the brow ...

Utilize Aframe to easily view and upload local gltf files

I've been working on a project to create a user-friendly panel for loading and viewing gltf models in real-time in A-frame. Here is the current workflow I am following: Using the input tag to load files from local storage. Using v-on-change to assi ...

Steer clear of duplicating patterns in vue templates

I have a significant issue with a component that needs to be repeated multiple times in the parent template due to the usage of v-if. The component code is as follows: <SelectCard v-for="(channel, index) in category.visibleChannels" :key="index + & ...

The footer seems to be losing its stickiness and not staying at the bottom when I

My goal is to create a sticky footer for my webpage. Once you click the add new sports button, a drawer slides out and the footer remains fixed at the bottom. However, as I scroll down the page, the footer moves up instead of staying in place. I have tried ...

"Implementing a feature in AngularJS where bootstrap modal utilizes the ENTER key press to trigger actions with two buttons,

I am working on a modal screen that allows users to create new publications and edit existing ones: <div class="modal-content"> <form role="form"> <div class="modal-header ng-scope"> <h3 class="modal-title">{{ items ...

Ng-show not updating when scope variable changes

Initially, I set the boolean flag of the infoWindow to false: $scope.infoWindow = false; Subsequently, I've added a google maps listener for a click event as shown below: google.maps.event.addListener(circle, 'click', function(event) { ...

Tips for efficiently moving through divs in a personalized single page application?

Exploring the world of JS frameworks and single page app functionality is a bit of a mystery to me. Currently, I have a pseudo single page app set up without any specific framework in place. The setup involves 3 tabs that toggle visibility for 3 different ...

Is it possible to maintain the maximum height and width of a div across all levels of zoom?

In the process of developing a web application, I encountered an issue regarding setting the width and height of a div to a fixed number, regardless of the zoom level. While I was successful in changing the background color of the div across all zoom level ...

Ensuring the model accurately reflects the input's value attribute in AngularJS

I am in the process of creating a set of image "radio buttons" where only one can be selected per group. However, as a newcomer to Angular, I'm facing difficulties in maintaining the value and using it as my ng-model. Additionally, I am looking for a ...

The function GetURLParameter(sParam) is displaying %20 as blank space in the webpage

I am facing an issue with a code that pulls URL parameters into the landing page. The problem is that it is including white spaces as %20. For example, if my URL parameter is: example.com/?title=my website, it would display my%20website on the page inste ...

Utilize JavaScript to parse HTML content retrieved through AJAX requests

My current project involves writing JavaScript code, specifically a Chrome extension, that needs to: Retrieve the contents of a web page using AJAX. Extract specific content from the page by identifying certain elements within the HTML string and retriev ...

Saving a variable within a for loop in JavaScript

Hey everyone, I could really use your help right now. Here's the code block I'm struggling with: function readyToSubmit(answerPack, answerArr, len) { for (var i = 0; i < answerArr.length; i++) { var questionId = answerArr[i].id; con ...

Encountering the error message: "TypeError [ERR_INVALID_ARG_TYPE]: The initial parameter should either be a string, Buffer instance, or Uint8Array."

Having trouble with the payment gateway API and subscription creation. Encountering an error that I can't seem to resolve even after debugging. Despite my best efforts, the error persists. The form and everything else seem to be in order, but the err ...

Does this configuration for the formkit seem correct?

import { createApp } from "vue"; import App from "./App.vue"; import router from "./router"; import { plugin, defaultConfig } from "@formkit/vue"; import "./assets/tailwind.css"; import "aos/dist/aos.c ...

Sending images from an external source to a client using Node.js and Express

I'm struggling with a problem. Assuming I have an external image URL, like this one from IMDb.com, . How can I display this image for the client? Currently, I have this: res.write('<img src="/http://ia.media-imdb.com/images/M/MV5BMTMyMzA5ODI ...

Stuck on an endless loop of the Ionic splash screen

Currently, I am facing an issue with my Ionic 1 project. Everything was functioning properly until a few days ago when the splash screen stopped disappearing on iOS, although it still does on Android. I have searched for solutions on Google but haven' ...