Triggering a click event within a Bootstrap popover

Clicking the inbox button triggers the inbox_open() function. When this function runs, three buttons appear in the inbox header but there is no onclick event listener attached to them. Make sure to review the code after the // inbox.open comment for critical lines:

b.onclick = function() { console.log("button was clicked"); }
and
inbox.setAttribute("title", poH.innerHTML);

// inbox
var inbox = document.getElementById("inbox");
var inbox_news = document.getElementById("inbox_news");

var poH = document.createElement("span");
var poC = document.createElement("span");

var new_from_to = [0, 2, 3];
var number_of_news = [2, 1, 2];
var news_price_data = [10, 20, 30, 40, 50];

// inbox.open
function inbox_open() {
  for (var i = 0; i < number_of_news.length; i++) {
    var b = document.createElement("button");
    b.innerHTML = (i + 1);
    b.className = "poH";
    b.onclick = function() {
      console.log("button clicked");
    }
    poH.appendChild(b);
  }
  inbox.setAttribute("title", poH.innerHTML);
}

// inbox.addEventListener
inbox.onclick = inbox_open();

// Allow BS 4 popover to run
$(document).ready(function() {
  $('[data-toggle="popover"]').popover();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<!-- HTML -->
<button id="inbox" class="btn btn-primary btn-sm" style="float: right; margin: 30px 30px 0 0;" data-toggle="popover" data-placement="left" data-html="true" title="" data-content="">inbox <span id="inbox_news"></span></button>

Answer №1

The issue at hand lies in the fact that the onclick function is not being properly bound to the buttons due to the unique behavior of Bootstrap's Popovers. To remedy this, you can include the following snippet of code to ensure that the onclick listener is added when the buttons are displayed:

$('#inbox').on('shown.bs.popover', function () {

    var btns = document.getElementsByClassName("poH");
    for (var i=0; i < btns.length; i++) {
        btns[i].onclick = function() { console.log("action"); };
    }

});

To implement this solution, simply insert the above code following your $(document).ready(...) declaration.

Answer №2

Preventing the onclick event on popover content is a common issue when using Bootstrap with any element. Attempting to bind an onclick event after the 'shown.bs.popover' event can result in the click behavior being prevented. The following code provides a solution to allow the popover content's onclick event to fire:

var inbox = document.getElementById("inbox");
var inbox_news = document.getElementById("inbox_news");

var poH = document.createElement("span");
var poC = document.createElement("span");

var new_from_to = [0, 2, 3];
var number_of_news = [2, 1, 2];
var news_price_data = [10, 20, 30, 40, 50];

// inbox.open
function inbox_open() {
  for (var i = 0; i < number_of_news.length; i++) {
    var b = document.createElement("button");
    b.innerHTML = (i + 1);
    b.className = "poH";
    b.click = function() {
      console.log("button clicked");
    }
    poH.appendChild(b);
  }
  inbox.setAttribute("title", poH.innerHTML);
}

// inbox.addEventListener
inbox.onclick = inbox_open();

$(document).ready(function() {
  $('[data-toggle="popover"]').popover();
  
  $('#inbox').on('shown.bs.popover', function () {
    for (var i=0; i < $('.poH').length; i++) {
        $('.poH')[i].onclick = function() { alert($(this).text()); };
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<!-- HTML -->
<button id="inbox" class="btn btn-primary btn-sm" style="float: right; margin: 30px 30px 0 0;" data-toggle="popover" data-placement="left" data-html="true" title="" data-content="">inbox <span id="inbox_news"></span></button>

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

Create a function that is determined by a specific hyperlink

I am looking to create a universal function that can work with all types of links on my pages. For example: If I click on a .pdf link, it should open a PDF viewer. If I click on a .mp3 link, it should open an audio player, and so on. However, I want to ...

Is it possible to customize the close icons on the autocomplete feature in Material UI?

Is there a solution to change the icon while keeping its function when clicked? I am looking to replace this Icon <Autocomplete multiple id="checkboxes-tags-demo" options={top100Films} disableCloseOnSelect getOpt ...

Editing the dimensions of the input in Bootstrap 4

Is there a way to adjust the width of the input and select elements? I want the input element to take up more space while the select element occupies less space. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel=" ...

Creating a custom design for a button using an external CSS file

I have an HTML code linked to a CSS file where I'd like to style buttons. The button styles are defined in the CSS file. Everything else is working fine, but when I attempt to apply the styled button, it reverts back to a standard HTML button unless ...

When the div is loaded, automatically navigate to the crucial li element within it, such as the one with the class "import

Welcome to my first webpage: <html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="comment"></div> <script type="text/ja ...

Flask is having trouble loading images within the static directory

I am facing an issue with loading two images in my HTML when the 'next' button is clicked. Initially, everything was working fine before I integrated the front end with Flask. The CSS and JS files are functioning properly, but the images are not ...

When a user clicks on an image, I would like to dynamically resize it using a combination of PHP

Although I have a good understanding of CSS and HTML, my knowledge of Javascript is limited. I am looking to add an interactive element to my website where an image enlarges gradually when clicked and smoothly moves to the center of the screen in one con ...

Prevent double tap selection

At times, I enable the user to click on the <li> or <span class="icon"> elements, but if they happen to click twice, it causes a bit of chaos and spreads the blue selection all over :/ To address this issue, I have come up with two solutions: ...

The <img> tag needs to dynamically adjust its size based on the width of its parent element, while ensuring it does not exceed its original dimensions

I spent hours working on my tribute page project on codepen and managed to pass 9 test cases. However, no matter what I try, I just can't seem to pass the last test case. My CSS code: #img-div { display: block; filter: grayscale(100%); width: 1 ...

The color of the progress bar shifts according to its value

In my MySQL database, there is a field called progress_profile where I input values ranging from 1 to 100. $progress = $row['progress_profile']; Within the bootstrap-bar code, the following snippet is implemented: <p class="bioheading">P ...

Guide to selecting a date using JavaScript in Selenium with Ruby

I'm having some trouble selecting a date from a date picker field using JavaScript in Selenium WebDriver. I've attempted the code below, which does navigate to the date window successfully, but I can't figure out how to execute the JavaScrip ...

Ensuring jQuery filter() works seamlessly with Internet Explorer versions 6, 7, and 8

On my webpage, I have implemented an ajax call using the jQuery library to handle a specific task. After making the ajax call, I need to parse the response message that is returned. However, I encountered an issue with Internet Explorer versions 6, 7, and ...

Display PHP array information in an HTML table

I am facing an issue with an array that contains a record set generated by the CodeIgniter model. When attempting to display these records in an HTML table using my view, the layout is not rendering correctly. Here is a snippet of my view: <html> & ...

Building a sleek and responsive navigation bar using HTML, CSS, and Bootstrap is

As a newcomer to programming and completely new to HTML, I am currently working on a class project for my Web Development course. The task involves creating a webpage for a fictional company named "DW Gift Company." One of the requirements for this project ...

Tips for sending a variable from Javascript to node.js, specifically connecting to MYSQL

Can you help me with a simple example on how to pass a variable from JavaScript to Node.js? I need to store the user input from a text box in Node.js and perform some actions. Client <!DOCTYPE html> <html> <body> <h2>HTML Forms< ...

HTML makes column text wrapping automatic

Is it feasible to implement text wrapping into two columns or more in HTML using solely CSS? I have a series of continuous text enclosed within p tags only, structured as follows: <div id="needtowrap"> <p>Lorem ipsum dolor sit amet, ...&l ...

Attempting to verify JavaScript input by utilizing OnClick and a custom function. Regardless of the content inputted, the system consistently confirms that the format is accurate

I am currently working on a project that involves an HTML file and an external JavaScript file. In the HTML file, there is user input and a validation button that triggers the courseValidation() function when clicked. However, I am facing an issue with the ...

Repairing the formatting of the content inside a dynamically growing div

Check out the code on this Fiddle link, <!DOCTYPE html> <body> <div class="test"> <h1>?</h1> <p>This paragraph gives more information that can be accessed by hovering over the question mark (Move your mouse awa ...

The red error text below the input becomes less visible when the input is focused on Windows, creating

My issue involves a basic input field and error validation message, both set against a dark background. The problem arises when the error text is displayed and I click on the input field - the error text suddenly loses contrast and appears "thinner." What& ...

Error encountered with the OffsetWidth in the Jq.carousel program

I am encountering an issue that I cannot seem to figure out. Unexpected error: Cannot read property 'offsetWidth' of undefined To view the code in question, click on this link - http://jsfiddle.net/2EFsd/1/ var $carousel = $(' #carouse& ...