Modal/Popover - 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 element, no JS required.
Demo
HTML
<!-- `popovertarget="pop-with-close"` on the `button` connects to `id="pop-with-close"` on the `dialog` -->
<button popovertarget="pop-with-close">
Toggle Popover with "close" button
</button>
<dialog popover="manual" id="pop-with-close">
<h2>I'm <code>manual</code> Popover 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
CodePen
See the Pen on CodePen.