'How do you create and modify popover in Bootstrap 5 using jquery?
Does someone know how I can create and add data to bootstrap 5 popover via javascript/jquery?
With bootstrap 3 I was able to do this:
$('#element').popover({ placement : 'left', trigger : 'focus', html: true });
let content_template = `<h1>Hello World!</h1>`;
$('#element').data('bs.popover').options.content = content_template;
But I can't figure out how I can do the same with bootstrap 5. The documentation doesn't mention anything about this. Does anyone know how popovers are managed in BS5?
Solution 1:[1]
You need to get instance of popover and then use popover_instance._config.content ="some message" to set new content inside your popover .
Demo Code :
new bootstrap.Popover(document.querySelector('[data-bs-toggle]'), {
placement: 'left',
trigger: 'focus',
html: true
})
//get instance
var popover_instance = bootstrap.Popover.getInstance(document.querySelector('[data-bs-toggle]'))
let content_template = `<h1>Hello World!</h1>`;
popover_instance._config.content = content_template;//set content
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="Popover title">Click to toggle popover</button>
Solution 2:[2]
If you plan on updating popover content multiple times you also need to call setContent() on popover instance. Like this
popoverInstance._config.content = "Hello world";
popoverInstance.setContent();
Solution 3:[3]
Use vanilla JavaScript instead of jQuery. The popover instance is returned from instantiation. You can then use this to modify the content...
const bsPopover = new bootstrap.Popover(document.querySelector('[data-bs-toggle]'), {
placement: 'left',
trigger: 'focus',
html: true
})
bsPopover._config.content = `<h1>Hello World!</h1>`;
bsPopover.setContent();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Swati |
| Solution 2 | Eugene |
| Solution 3 |
