Search code examples
javascriptjqueryhtmltwitter-bootstrappopover

Popover not showing when the html content got added through innerHTML


This is something that has bothered me a lot and would be thankful if someone could help me.

I want to take the innerHTML from an already existing popover and put it in another div. When I do this, the popover inside the other div is not working.

This is my head:

<link
  rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
  integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
  crossorigin="anonymous"
/>

<script
  src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
  integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
  crossorigin="anonymous"
></script>

<script
  src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
  integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
  crossorigin="anonymous"
></script>

<script
  src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
  integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
  crossorigin="anonymous"
></script>

Body:

<div id="myPopover" class="com">
  <a
    class="arrow"
    tabindex="0"
    role="button"
    data-toggle="popover"
    data-trigger="hover"
    title="Title"
    data-content="Content"
    ><img src="https://i.imgur.com/BQpNMZA.jpg"
  /></a>
</div>

<button onclick="myFunction()">Click here</button>

<div id="demo">hej</div>

Script:

$(function() {
  $('[data-toggle="popover"]').popover();
});

function myFunction() {
  document.getElementById('demo').innerHTML = document.getElementById(
    'myPopover'
  ).innerHTML;
}

When I press the button the div with the id "demo" is supposed to get the innerHTML from the div with id "myPopover". This seems to work when I open the inspector in firefox, the problem is that the popover is not displayed.


Solution

  • You will need to add this line to myFunction()

    $('[data-toggle="popover"]').popover();
    

    Because you are adding the inner html from the myPopover div to the DOM, you will need to initialize the popover on the newly created element. Popover will not know about it otherwise.