Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap popover, image as content

I'm trying to this:

$("a[rel=popover]").popover({
    html:       true,
    trigger:    'hover',
    content:    '<img src="'+$(this).data('img')+'" />'
});

but it doesn't work because the $(this).data('img') doesn't work.

Why I do this, I've got conflicts with templating and html in the data-content attribute. So I place the image source in a data-img attribue and like to grab that en place it into a img element.

I've tried this, but works not fully:

$("a[rel=popover_img]").popover({
    html:       true,
    trigger:    'hover',
    content:    '<img src="#" id="popover_img" />'
}).hover(function(){
    $('#popover_img').attr('src',$(this).data('img'));
});

I hope somebody can help me out :)

like image 918
Roy Avatar asked Nov 28 '12 11:11

Roy


People also ask

How do I customize bootstrap popover?

To create a popover, you need to add the data-bs-toggle="popover" attribute to an element. Whereas, popover's title and its content that would display upon trigger or activation can be specified using the title and data-bs-content attribute respectively. Here is the standard markup for adding a popover to a button.

How do you use bootstrap popovers?

To create a popover, add the data-toggle="popover" attribute to an element. Note: Popovers must be initialized with jQuery: select the specified element and call the popover() method.

How do you dispose of popovers?

You just do: $("[data-toggle='popover']"). popover('hide'); Or you can use destroy if you need to or prefer to.

How do I show popover on hover?

Set the trigger option of the popover to hover instead of click, which is the default one. Or with an initialization option: $("#popover"). popover({ trigger: "hover" });


2 Answers

As it currently stands your this is referencing the current scope, whereas you want to be referencing the element which the Popover instance is attached to. This is done simply by wrapping the expression you have for content in a function:

$('a[rel=popover]').popover({
  html: true,
  trigger: 'hover',
  content: function () {
    return '<img src="'+$(this).data('img') + '" />';
  }
});

See demo:

Plunker

like image 92
merv Avatar answered Sep 22 '22 18:09

merv


An alternative to what merv proposed, for simplicity you can embed a lot of the jquery properties to the html and leave the jquery lightweighted e.g

<a href="#" data-toggle="popover" title="Popover Header" data-html="true" data-content="<img src='http://localhost:15249/img1.jpg' width='200' />">Toggle popover</a>

and call the popover via jquery

$('["popover"]').popover()

Points to note when using this approach, the data-html should be set to true, else the image is not interpreted as html but as text

like image 12
Tolani Avatar answered Sep 22 '22 18:09

Tolani