When we created popovers in the previous few lessons, we had to make them manually and add them into the HTML. This method is great for creating custom popovers.
But if you need a generic popover that contains one paragraph of text, you can create the popover programmatically.
Preparations
Let’s start by deleting the bottom popover. We’ll create it with JavaScript.
<!-- Delete this -->
<div id="pop-4" class="popover" data-position="bottom">
<p>The quick brown fox jumps over the lazy dog.</p>
</div>
Making a popover with JavaScript
Let’s create a function called createPopover to make a popover.
const createPopover = _ => {
// ...
}
Each popover is a <div> element. We can create the <div> with createElement.
Finally, the popover needs content. We can send content from the trigger to the popover through another custom attribute. Let’s call it data-content.
The popover will always be placed as a direct descendant of the <bod> element. Since that’s the case, we can append the popover to the DOM inside createPopover.
We assumed all popovers are in the DOM in the forEach code.
popoverTriggers.forEach(popoverTrigger => {
// This assumes the popover is in the DOM
const popover = document.querySelector(`#${popoverTrigger.dataset.target}`)
// ...
})
But we know that assumption is invalid now. We need to create popovers when we can’t find them in the DOM.
popoverTriggers.forEach(popoverTrigger => {
let popover = document.querySelector(`#${popoverTrigger.dataset.target}`)
if (!popover) {
createPopover(popoverTrigger)
}
// ...
})
Next, we need to get the created popover from the DOM to use it in calculatePopoverPosition. We can get the popover if we return the popover from createPopover.