Search code examples
jquerybootstrap-popover

chain of bootstrap popovers using jquery


I am trying to open sub-menu from a popover in another popover, but i am having trouble doing that. Here is the sample code

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

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

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<ul id="menu1" class="dropdown-menu">
    <li id="instance_1" data-toggle="popover2" style="cursor:pointer">Instance 1</li>
    <li id="instance_2">Instance 2</li>
</ul>
<ul id="menu2" class="dropdown-menu">
    <li id="instance_3">Instance 3</li>
    <li id="instance_4">Instance 4</li>
</ul>

<button type="button" class="btn btn-lg btn-Primary" 
        data-toggle="popover1">
  Click to toggle popover
</button>

<script>
        $('[data-toggle="popover1"]').popover({
            html: true,
            placement: 'auto right',
            container: 'body',
            trigger: 'click',
            template: '<div id="x" class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content"><div class="data-content"></div></div></div>',
            content: function () {
                return $('#menu1').html();
            }
        });
        $('[data-toggle="popover2"]').popover({
            html: true,
            placement: 'auto right',
            container: 'body',
            trigger: 'click',
            template: '<div id="y" class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content"><div class="data-content"></div></div></div>',
            content: function () {
                return $('#menu2').html();
            }
        });
</script>

Can Someone help me in understanding how to do this. Thanks in advance!!


Solution

  • The issue here is that when the $('[data-toggle="popover2"]').popover() function is being called, it adds the listener only to the initial template. This listener does not carry over when you populate the first popover based on that HTML. The solution then is to run the .popover() function again after that content is generated (when the popover is opened). Here is a codepen demonstrating this with a click listener on the first popover:

    https://codepen.io/zeiv/pen/BJmowO

    The above pen will take some fiddling with to get all the details right (e.g., closing the first popover does not close the second), but hopefully you get the idea. I can work on it some more if you need help with that.