activate the bootstrap popover by double-clicking instead of a single click

Clicking on a certain div triggers a popover to display another div, which works initially. However, once the popover is removed by clicking outside the div, it requires two clicks to trigger the popover again. How can this be fixed so that it always works with just one click? Any assistance would be greatly appreciated. Thank you in advance.

Update:

An attempt was made to solve this issue but it did not work as expected. The proposed solution only partially worked on Bootstrap 4 and did not work at all on Bootstrap 5. Here is the attempted solution:

$('body').on('hidden.bs.popover', function (e) {
    $(e.target).data("bs.popover")._activeTrigger.click = true
});

$(function() {
  $(".testDiv").popover({
    container: 'body',
    html: true,
    placement: 'bottom',
    sanitize: false,
    content: function() {
      $('.testDivCon').show()
      $('.wifiInfoContent').append('<button class="testButton">Click Me</button>')
      return $('.wifiInfoContent').html();
    }
  });

});

$('.testDivCon').on('click', function() {
  $('.popover').remove()
  $('.testDivCon').hide()
})

$(document).on('click', '.testButton', function() {
  console.log('clicked')
})
.testDivCon {
  display: none;
  position: absolute;
  top: 0%;
  left: 0%;
  width: 100%;
  height: 100%;
  background-color: green;
}

.testDiv {
  position: absolute;
  top: 10%;
  left: 20%;
  width: 20%;
  height: 15%;
  background-color: black;
}

.wifiInfoContent {
  display: none;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceaca1a1babdbabcafbe8efbe0ffe0fd">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72101d1d06010600130232475c435c41">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01636e6e75727573607141342f302f32">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div class="testDivCon"></div>
<div class="testDiv"></div>

<div class="wifiInfoContent"></div>

Answer №1

To successfully close the popover, follow these steps:

$('.testDiv').popover('hide');

$(function() {
  $(".testDiv").popover({
    container: 'body',
    html: true,
    placement: 'bottom',
    sanitize: false,
    content: function() {
      $('.testDivCon').show()
      $('.wifiInfoContent').append('<button class="testButton">Click Me</button>')
      return $('.wifiInfoContent').html();
    }
  });

});

$('.testDivCon').on('click', function() {
  $('.testDiv').popover('hide');
  $('.testDivCon').hide();
})

$('.testDiv').on('click',function() {
  $('.testDivCon').hide()
});

$(document).on('click', '.testButton', function() {
  console.log('clicked')
});
.testDivCon {
  display: none;
  position: absolute;
  top: 0%;
  left: 0%;
  width: 100%;
  height: 100%;
  background-color: green;
}

.testDiv {
  position: absolute;
  top: 10%;
  left: 20%;
  width: 20%;
  height: 15%;
  background-color: black;
}

.wifiInfoContent {
  display: none;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[unique-link]/dist/css/bootstrap.min.css" integrity="[unique-integrity]" crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/[unique-link]/dist/js/bootstrap.min.js" integrity="[unique-integrity]" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[unique-link]/dist/js/bootstrap.bundle.min.js" integrity="[unique-integrity]" crossorigin="anonymous"></script>

<div class="testDivCon"></div>
<div class="testDiv"></div>

<div class="wifiInfoContent"></div>



You can achieve this without using jQuery and utilize bootstrap 5 instead. Here's how:

const popoverTrigger = document.querySelector('.testDiv');
const popover = new bootstrap.Popover(popoverTrigger, {
  html: true,
  sanitize: false,
  content: '<button class="testButton">Click Me</button>'
});

let testDivConShown = false;

popoverTrigger.addEventListener('click', function(){
  testDivConShown = !testDivConShown;
  document.querySelector('.testDivCon').style.display = testDivConShown ? 'block' : 'none';
});

document.querySelector('.testDivCon').addEventListener('click', function() {
    popover.hide();
    testDivConShown = false;
    document.querySelector('.testDivCon').style.display = 'none';
});
  
document.body.addEventListener('click', function(e) {
  if(e.target.classList.contains('testButton'))
  console.log('button clicked');
});
.testDivCon {
  display: none;
  position: absolute;
  top: 0%;
  left: 0%;
  width: 100%;
  height: 100%;
  background-color: green;
}

.testDiv {
  position: absolute;
  top: 10%;
  left: 20%;
  width: 20%;
  height: 15%;
  background-color: black;
}
<link href="https://cdn.jsdelivr.net/npm/[unique-link]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="[unique-integrity]" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[unique-link]/dist/umd/popper.min.js" integrity="[unique-integrity]" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[unique-link]/dist/js/bootstrap.min.js" integrity="[unique-integrity]" crossorigin="anonymous"></script>

<div class="testDivCon"></div>
<div class="testDiv" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="bottom"></div>

<div id="wifiInfoContent" class="d-none"><button class="testButton">Click Me</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

Is there a way to dynamically include a peer dependency in a file that is bundled using webpack?

I am currently developing a plugin that relies on jQuery as a peer dependency. However, when I attempt to import this plugin into my primary project (which already has jQuery installed), I encounter the following error: Module not found: Error: Can't ...

Issues with jQuery validation in Struts2 form verification

My application is built on the struts2 framework, with jquery validation for client-side form input validation. However, I've encountered some compatibility issues between the two. I have a UserBean Class that needs to be included. The following cod ...

Tips for customizing the appearance of Java FX TableView column headers with CSS

I am relatively new to JavaFX and delving into CSS stylesheets, as well as using stackoverflow. I am curious about how one can customize the styling of a table column header. This is what my current column header looks like: Current appearance of my table ...

Effective HTML element placement with CSS styling

My HTML code includes a form containing a table. Take a look: This is the Code I'm Using: <html> <head></head> <body> <form onsubmit="" id="form1" action="" method="post" name="form1" style="position: rela ...

A current issue lies in the fact that node.js is failing to update

I'm currently working on creating a functionality that involves reading a CSV file and checking if the headers are correct before proceeding. Below is the code snippet: let validHeaders = false; fs.createReadStream(path) .pipe(csv.parse({headers : ...

Why do developers opt for getServerSideProps() over a standard asynchronous function in their code?

Recently, I decided to experiment with the getServerSideProps() function. While I understand it must have its purpose, to me it seems similar in utility to a typical async function. Take for example my current task of retrieving user data using Prisma and ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

The request body parser for the express POST method appears to be devoid of

After encountering similar issues on Stack Overflow, I discovered a solution involving the use of: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); However, despite implementing this solution, the log for req.body is still ...

What is causing the sorting table to fail in React when using useState?

import React, { useState } from "react"; import "./App.css"; const App = () => { const [data, setData] = useState([ { rank: 1, name: "John", age: 29, job: "Web developer", }, { rank: 2, name: "Micha ...

Error message: Unable to find child element in Selenium WebDriver

I'm currently dealing with a registration page where I encountered an issue. During my testing phase, I attempted to register without inputting a first name. Upon clicking the register button, I expected to see a 'Required' notification la ...

Password confirmation on the login screen will be displayed in a single line

As someone who is relatively new to HTML/CSS, most of what I have learned has come from this platform or by searching for answers online. I am nearing completion of my assignment, but I am struggling to figure out how to display two label words on the same ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

Is it possible to combine Ajax, JS, HTML, PHP, and MySQL in a single project?

I am looking to create a web application and wondering if I can integrate Ajax, JavaScript, HTML, PHP, and MySQL all together? ...

Is it possible to use JavaScript or jQuery to call a WCF Service and retrieve a collection of System.IO.Stream objects?

I am developing a WCF service that will be utilized by plain JavaScript on the client side, as well as some jQuery JavaScript. 1) How can I set up the plain client JavaScript to call the WCF Service in a manner that retrieves a collection of System.IO.Str ...

What is causing my Vue leave transition to malfunction?

Currently, I am utilizing vee validate for my form validation. Specifically, I have implemented vue transition to handle the display of validation errors in the following manner: <input type="text" name="name" v-validate="'required'"> < ...

Using JavaScript to parse JSON data generated by PHP using an echo statement may result in an error, while

I am facing an issue with parsing a JSON string retrieved from PHP when the page loads. It's strange that if I send an AJAX request to the same function, the parsing is successful without any errors. The problem arises when I attempt to do this: JSON ...

Enhance your JQuery skills by implementing variables within the .css() function

Attempting to randomly assign values to an image's left and right properties using JQuery. Here is the code snippet: var sides = ["left", "right"] var currentSide = sides[Math.floor(Math.random() * sides.length)]; $("#"+currentImage).css({currentSide ...

The Google map only displays a quarter of the screen on the left side

Currently, I am working on integrating Google Maps into my project. I have successfully implemented Google Maps services, but I am facing an issue where the map only displays in the top left corner of the container when the page is refreshed. Essentially ...

Error: Unable to access the 'location' property because it is undefined

Having trouble uploading a product along with an image using AWS S3 (Multer and MulterS3). Every time I try it in Postman, I get the error message "TypeError: Cannot read property 'location' of undefined" specifically pointing to the line where t ...

If you invoke revokeObjectURL, Chrome will fail to display Blob images

-----update------ After some investigation, I found that commenting out window.URL.revokeObjectURL( imgSrc ); fixed the issue in all browsers. It seems like Chrome was revoking the URL too early. I am curious to understand why this behavior occurs, and if ...