Home / Learn / How do you build a dropdown and tooltip with smooth motion?

How do you build a dropdown and tooltip with smooth motion?

Dropdowns and tooltips open and close dozens of times per session, and their motion makes the difference. You will learn a soft pop-in with logical positioning that fits both directions.

Steps

  1. Put the button and menu inside a position: relative wrapper, and make the menu absolute below the button.
  2. Place the menu with inset-inline-start and top: calc(100% + 6px) so it hugs the button in either direction.
  3. In JavaScript, toggle hidden and update aria-expanded, and close the menu with Escape and on outside click.
  4. Add a short entrance: opacity plus a tiny downward slide, no longer than 0.2 seconds.
  5. Under prefers-reduced-motion, drop the animation so the menu appears instantly.

The code

HTML

<div class="dropdown">
  <button id="ddBtn" aria-haspopup="true" aria-expanded="false" aria-controls="ddMenu">القائمة</button>
  <ul id="ddMenu" class="dropdown-menu" hidden>
    <li><a href="#">الملف الشخصي</a></li>
    <li><a href="#">الإعدادات</a></li>
    <li><a href="#">تسجيل الخروج</a></li>
  </ul>
</div>

<script>
const ddBtn = document.getElementById("ddBtn");
const ddMenu = document.getElementById("ddMenu");

ddBtn.addEventListener("click", () => {
  const willOpen = ddMenu.hidden;
  ddMenu.hidden = !willOpen;
  ddBtn.setAttribute("aria-expanded", String(willOpen));
});

document.addEventListener("keydown", (event) => {
  if (event.key === "Escape" && !ddMenu.hidden) {
    ddMenu.hidden = true;
    ddBtn.setAttribute("aria-expanded", "false");
    ddBtn.focus();
  }
});

document.addEventListener("click", (event) => {
  if (!event.target.closest(".dropdown") && !ddMenu.hidden) {
    ddMenu.hidden = true;
    ddBtn.setAttribute("aria-expanded", "false");
  }
});
</script>

<style>
.dropdown {
  position: relative;
  display: inline-block;
}
.dropdown-menu {
  position: absolute;
  inset-inline-start: 0;
  top: calc(100% + 6px);
  margin: 0;
  padding: 6px;
  list-style: none;
  min-width: 170px;
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  animation: dd-pop 0.18s ease;
}
.dropdown-menu a {
  display: block;
  padding: 8px 10px;
  border-radius: 6px;
  text-decoration: none;
  color: #0f172a;
}
.dropdown-menu a:hover {
  background: #f1f5f9;
}
@keyframes dd-pop {
  from { opacity: 0; transform: translateY(-4px); }
}
@media (prefers-reduced-motion: reduce) {
  .dropdown-menu { animation: none; }
}
</style>

RTL & Arabic notes: inset-inline-start anchors the menu to the button's start edge in both Arabic and English, and the Arabic links render fully joined.

Didn't find the motion you need? Request it from the Vellox team.