zenn_waapi_demo06

by 6242ea4

HTML

<button id="show">トーストを表示</button>
<div class="toast" hidden>保存しました</div>

CSS

.toast {
  position: fixed;
  left: 16px;
  bottom: 16px;
  padding: 12px 20px;
  border-radius: 8px;
  background: #333;
  color: white;
}

JavaScript

const button = document.querySelector('#show');
const toast = document.querySelector('.toast');

async function showToast(toast) {
  // 1. 下からふわっと表示する
  toast.hidden = false;
  await toast.animate(
    [{ opacity: 0, translate: '0 16px' }, { opacity: 1, translate: '0 0' }],
    { duration: 200, easing: 'ease-out' }
  ).finished;

  // 2. 2 秒待つ
  await new Promise((resolve) => setTimeout(resolve, 2000));

  // 3. 消えるアニメーションが終わってから非表示にする
  await toast.animate({ opacity: [1, 0] }, { duration: 200 }).finished;
  toast.hidden = true;
}

button.addEventListener('click', async () => {
  button.disabled = true;
  await showToast(toast);
  button.disabled = false;
});