I try to find a solution, I would like to update just a part of data-content of popover. Exemple of code:
<div >
<i
id="popover_help"
data-toggle="popover"
data-placement="right"
data-content="<p>Some static text
<span class='update-text'>Dynamic text to update</span>
</p>"
data-html="true">
</i>
</div>
<button onClick="updatePopoverContent()">Click to update</button>
<script>
function updatePopoverContent() {
$('.popover-wrapper .hover_content')???;//and something like attr(‘data-content .update-text’, ‘new text’)
}
</script>
to show popover I use:
$(".hover_content").popover({
trigger: "manual",
animation: false,
delay: {
"hide": 30
}
}).on("mouseenter", function() {
var _this = this;
$(this).popover("show");
$(".popover").on("mouseleave", function() {
$(_this).popover('hide');
});
}).on("mouseleave", function() {
var _this = this;
if (!$(".popover:hover").length) {
$(_this).popover("hide");
}
});
Is it possible to change just a part of 'data-content' text? Maybe someone can give some advice? Thank you in advance!
CodePudding user response:
Using bootstrap-4, you can update the attribute data-content
.
NB: you cannot update the .data
value using jquery's .data("content", newValue)
as it appears the popper reads the attribute directly each time instead of honouring the data convention.
$("#popover_help").attr("data-content", replacementHtml);
To update just the update-text
part, you can read the HTML, parse it, use jquery to change it, then write it back as HTML:
var html = $("#popover_help").data("content");
var parsed = $("<div/></div>").html(html);
parsed.find("span").text("Updated text");
$("#popover_help").attr("data-content", parsed.html());
You can apply this to a .class to update all if you have more than one, here's an example.
$(function () {
$('[data-toggle="popover"]').popover()
})
function updatePopoverContent() {
$(".hover_content").each(function() {
var html = $(this).data("content");
var parsed = $("<div/></div>").html(html);
parsed.find("span").html("<strong>Updated</strong> text");
$(this).attr("data-content", parsed.html());
// doesn't update if currently shown, so hide then show if desired
$(this).popover("hide");
//$(this).popover("show");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<br/>
<div >
<i
id="popover_help"
data-toggle="popover"
data-placement="right"
data-title="Example"
data-content="<p>Some static text
<span class='update-text'>Dynamic text to update</span>
</p>"
data-html="true">
click me
</i>
</div>
<hr/>
<button onClick="updatePopoverContent()">Click to update</button>