🛠️ Popover: Dynamic ID

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠️ Popover: Dynamic ID

If we create a popover with JavaScript, we don’t need to think of an id for it. We can generate one with JavaScript. This makes it easier for the user to create a popover.

There are three steps:

  1. Remove the manually written data-target
  2. Generate an id
  3. Add the id as the trigger’s data-target value

First, we remove data-target from the trigger.

<button
  class="popover-trigger"
  data-popover-position="bottom"
  data-content="Hello world!"
> ... </button>

Next, we’ll generate an id with generateUniqueString.

const generateUniqueString = length => {
  return Math.random().toString(36).substring(2, 2 + length)
}
const createPopover = popoverTrigger => {
  const popover = document.createElement('div')
  popover.id = generateUniqueString(5)
  // ...
}

Finally, we add generated id as the trigger’s data-target value.

const createPopover = popoverTrigger => {
  // ...
  const id = generateUniqueString(5)
  popover.id = id
  popoverTrigger.dataset.target = id
  // ...
}

That’s it!