NoLoJS logo

Offscreen Content - Add Close Button

Using the native HTML popover attribute, you can also use the native HTML popovertargetaction attribute to create a native open/close method for your modal/popover/dialog element, no JS required.

Demo

I'm some Related Content with a "close" button!

A manual popover can not be "light dismissed".

Opening a manual popover does not automatically close any other manual popovers that were open, but will close any auto popovers that were open.

Clicking the element that opened an auto popover a second time will close the popover that it opened.

You can also add a "close" button to any popover; note the `popovertargetaction="hide"` on the button below.

The default CSS is initially `position: fixed` and hidden offscreen.

When opened, the default CSS positions the popover center/center on screen.

HTML

<!-- `popovertarget="pop-with-close"` on the `button` connects to `id="pop-with-close"` on the `dialog` -->
<button popovertarget="pop-with-close">
   Toggle Related Content with "close" button
</button>
<dialog popover="manual" id="pop-with-close">
  <h2>I'm some Related Content with a "close" button!</h2>
  <p>A <code>manual</code> popover can <strong>not</strong> be "light dismissed".</p>
  <p>Opening a <code>manual</code> popover does <strong>not</strong> automatically close any other <code>manual</code> popovers that were open, but <em>will</em> close any <code>auto</code> popovers that were open.</p>
  <p>Clicking the element that opened an <code>auto</code> popover a second time will close the popover that it opened.</p>
  <p>You can also add a "close" button to any popover; note the `popovertargetaction="hide"` on the button below.</p>
  <p>The default CSS is initially `position: fixed` and hidden offscreen.</p>
  <p>When opened, the default CSS positions the popover center/center on screen.</p>
  <button popovertarget="pop-with-close" popovertargetaction="hide">×</button>
</dialog>

CSS

/* If you wish to re-position the popover via CSS... */
dialog {
  margin: 0; /* Remove the default center/center */
  position: relative; /* Replaces the default position: fixed */
  top: 10%;  /* Provide a different top/left */
  left: 33%;
}
/* Position the close button where you like */
dialog button {
  position: absolute;
  top: .5rem;
  right: 1em;
}

JS

No JS required.

Baseline

[`popover`](https://webstatus.dev/features/popover)

CodePen

See the Pen on CodePen.