Search code examples
javascriptjquerycssbootstrap-4jsfiddle

Why does my Popover work when elements are created via HTML but not dynamically via JavaScript?


I'm creating a method to add multiple popovers that look like this:

My first JsFiddle, working output (click to view screenshot)

The above was what I've managed to create so far using the following code in my first JsFiddle:

Example 1 - Working! (now a broken code link)

I've created exactly the same DOM elements in the second JsFiddle (with same references to bootstrap, popper, material-icons, jquery, etc and the same css and .popover() function and settings) but for some reason my second example does not work. I do actually have a working popover made using document.createElement() elements on my main site so I don't know why this one isn't working.. I've tested this outside of JsFiddle to no good end, also. PLEASE HELP!

The link to my second JsFiddle: Example 2 - Sadly, not working! But why?? (now a broken code link)

EDIT: This lovely man just fixed my code in less than half an hour since the post was posted! Very happy with @MichaelWhinfrey and Stack Overflow for this! Here is the answer, which I will accept now:

seems like the popover function needs to be run after the elements are created, initialising them in a $(document).ready() may be the solution you're after. I updated your fiddle to include an example jsfiddle.net/0cwe1v9yMichael Whinfrey 25 mins ago (2019-04-30 11:33:17Z)


Solution

  • Re-applying the popover after everything is loaded using the .popover-icon selector seems to resolve the issue.

    $(document).ready(function (){
      $(".popover-icon").popover({
            html: true,
            animation: true,
            placement: "right",
            trigger: 'focus',
            content: function() {
                var content = $(this).attr("data-popover-content");
                return $(content).children(".popover-body").html();
            }
        });
    });