Popover api usage - simple menu

by Julien Roche

HTML

<button name="menu" popovertarget="mypopover">Menu A</button>
<div id="mypopover" popover="auto">
  <div>
    <button popovertarget="mypopover" popovertargetaction="hide">Option A</button>
  </div>
  <div>
    <button popovertarget="mypopover" popovertargetaction="hide">Option B</button>
  </div>
</div>

CSS

html,
body {
  border: none;
  height: 100%;
  margin: 0 0 0 0;
  padding: 0 0 0 0;
  width: 100%;
}

body {
  align-items: center;
  display: flex;
  justify-content: center;
}

button {
  background-color: white;
  border: 1px solid black;
  border-radius: 0.5rem;
  color: black;
  cursor: pointer;
  font-weight: bold;
  margin: 0.25rem;
  padding: 0.5rem;
  user-select: none;

  &:hover {
    background-color: lightgray;
    box-shadow:
      inset 1px 1px 2px lightslategray,
      inset -1px -1px 2px lightgrey;
  }

  &[name="menu"] {
    anchor-name: --menu;
  }
}

[popover="auto"] {
  background: lightslategray;
  border-radius: 0.5rem;
  box-shadow: 1px 1px 3px lightslategray;
  border: none;
  text-align: center;

  /*.Anchoring */
  bottom: calc(anchor(top) + 1rem);
  align-self: anchor-center;
  justify-self: anchor-center;
  position-anchor: --menu; /* Important to have a smooth animation (and so we should declare anchor-name on the button */

  /* Animation */
  /* See https://nerdy.dev/using-starting-style-and-transition-behavior-for-enter-and-exit-stage-effects */
  opacity: 1;
  transition: opacity .5s ease-in, bottom .5s ease-in, display .5s ease-in;
  transition-behavior: allow-discrete; /* For exit */

  &:not(:popover-open) {
    bottom: anchor(bottom);
    opacity: 0;
  }

  @starting-style { /* Add properties to animate on opening */
    bottom: anchor(bottom);
    opacity: 0;
  }

  /* Content */
  & button {
    width: 10rem;
  }
}

JavaScript

const popoverElement = document.querySelector('[popover]');
popoverElement.addEventListener(
  'click',
  (event) => {
    if (event.target.tagName === 'BUTTON') {
      //popoverElement.hidePopover(); // don't if you use popoveraction="hide"
      setTimeout(() => {
        alert(`You vahe clicked on button: ${event.target.textContent}`)
      }, 150);
    }
  },
  false
);