Instead of the data being hardcoded, I want it to retrieve it from a html file, a template if you will. How can I do this? Let's say I have another html file with a <h1>
and a <body>
, and the popover should get the data from it (header/body of the popover)
<button type="button" class="btn btn-default" title="Help" data-toggle="popover" data-content="423241421453453"><span class="glyphicon glyphicon-info-sign" style="font-size: 20px; padding-top:5px"></span></button>
</div>
$(document).ready(function popover() {
$('[data-toggle="popover"]').popover();
});
Lets say you have a template like this :
<h1>header</h1>
<body>this is a test</body>
Then add the template filename as a data-templatefile
attribute to your button markup :
<button type="button" data-templatefile="template.html" class="btn btn-default" title="Help" data-toggle="popover"><span class="glyphicon glyphicon-info-sign" style="font-size: 20px; padding-top:5px"></span></button>
Then initialise the popover like this :
$('[data-toggle="popover"]').popover({
html : true,
content : function() {
return loadContent($(this).data('templatefile'))
}
});
This was straigt forward. The loadContent()
needs to be more tricky. If you use jQuery to parse the content you will see that the <body>
tag is stripped out. This is the browser doing that, not jQuery. But you can use a DOMParser
instead to extract exactly those tags you want to use in the popover :
function loadContent(templateFile) {
return $('<div>').load(templateFile, function(html) {
parser = new DOMParser();
doc = parser.parseFromString(html, "text/html");
return doc.querySelector('h1').outerHTML + doc.querySelector('body').outerHTML;
})
}