Bootstrap - Programmatically attach and show popover to an element
Asked Answered
D

3

14

I'm using Bootstrap v3 and I'm trying to show a popover programmatically, next to an element, when the page loads. There is no popover markup in the DOM. I want to create and show it in JQuery.

I've tried this but it doesn't work.

$( document ).ready(function() {
   $('.theElement').popover({
            placement:'right',
            trigger:'manual',
            html:true,
            content:'popover content'
        });
   $('.theElement').popover('show')
});

I get a "TypeError: Argument 1 of Window.getComputedStyle is not an object" error in console. I'm assuming this is caused by the above.

Dicephalous answered 6/2, 2015 at 10:31 Comment(4)
That should work fine. bootply.com/xqcvgLv7aU Check that jQuery and Bootstrap are referenced properly in your page.Shanghai
its working fine in this fiddleColonialism
I've found the problem. The element I was attaching to was also programmatically generated, so I had to make sure the popover was called after the element was added to the DOM. Thanks guys :)Dicephalous
Just stumbled upon this. Quick tip, there's no need to select the element twice, just chain .popover('show') to your previous popover() call.Kaczmarek
P
6

Try this

$( document ).ready(function() {
   $('.theElement').attr('data-placement','right')
   //add all atributes.....

   //and finally show the popover
   $('.theElement').popover('show')
});
Pygmy answered 27/4, 2016 at 1:56 Comment(0)
K
1
    $("[wf-popover]").popover({
        html : true,
        content: function() {
          var content = $(this).attr("wf-content");
          return content;
        },
        title: function() {
          var title = $(this).attr("wf-title");
          //return $(title).children(".popover-heading").html();
          return title;
        },
        placement: function() {
            var my = this.$element.attr('wf-popover')
            return my;
        },
        trigger: 'hover'
    });

element

<img src="profile.jpg" wf-popover="left" wf-content="<img src='profile_big.jpg' width=500 height=500 />" data-original-title="" title="">
Katelyn answered 28/2, 2018 at 6:2 Comment(0)
P
1

Try, calling this after the popover is shown

$('.popover').click(function() { $(this).hide(); });

Is the easiest approach.

Pampero answered 23/3, 2022 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.