1

In the navbar area, I want to add an About button, when it's clicked, there's a popover showing some general information. But it's not working

The html

<li class="nav-item">
<button class="btn btn-outline-primary text-sm-center nav-link font-weight-bold" data-toggle="popover" title="About this page" data-content="Test" id="B_About">
About
</button>
</li>

and the script to initialize it

$( document ).ready(function() {
    $('#B_About').popover({
    container: 'body'
  });
});

bootstrap.min.js & bootstrap.bundle.min.js are included.

Is there's any issue here?

Solaris_9
  • 181
  • 2
  • 15
  • 1
    I've set up a code pen example: https://codepen.io/r3dst0rm/pen/bjmjxm - For me it is working there. Can you verify that? – r3dst0rm Aug 08 '18 at 07:11
  • @r3dst0rm, thanks for you answering. But I find a weird thing now. even the $('#B_About').click(function() {}) couldn't be fired in my env. If I use $(document).on('click', '#B_About', function() {}), it could work, but only one click. Then nothing happens... – Solaris_9 Aug 08 '18 at 07:27
  • Can you remove the $(document).ready(...) part and just use `$('#B_About').popover({ container: 'body' });` other than that, what jQuery version are you using? And does your dev console output any errors? – r3dst0rm Aug 08 '18 at 07:38
  • I'm using JQuery-3.3.1. If I change the code like this: $(document).on('click', '#B_About', function(e) { $('#BAbout').popover('toggle'); e.preventDefault(); console.log(e.type); }); it will work only for the 1st click, then it will not work again! I don't understand. No error in the console. – Solaris_9 Aug 08 '18 at 07:42

1 Answers1

0

After digging into the issue, I found out it's linked to event delegation, because my button was drawn dynamically by the script.

Then I changed my script as below, it somehow works quite well:

document.addEventListener('click', function (e) {
    if (e.target.id == 'B_About') {
        $('#B_About').popover();
    }
}, false);

I prefer this page for a good explanation on event delegation.

Daniel Selvan
  • 959
  • 10
  • 23
Solaris_9
  • 181
  • 2
  • 15