0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ChatGPTとDevToolsで3ヶ月放置されたモーダルバグを1日で直した話

Posted at

発生していた問題

  • JavaScript単体のSPA(Single Page Application)
  • モチーフ選択後、モーダル(ポップアップUI)が表示される仕様
  • 本来:モチーフをクリックした時だけモーダルが開く
  • 実際:ページ遷移後、何もしていないのに勝手に開く

バグの調査手順(+ChatGPTの使い方)

① DevToolsで「何が起きたか」を追う

modal.classList.remove('hidden');

この1行が、なぜか画面遷移時に呼び出されていた

  • openModal() 関数が DOMContentLoaded 時にも呼ばれている?
  • もしくはイベントバインドの重複か?

② ChatGPTに相談

私が聞いたプロンプト:

「画面遷移時にJSのモーダルが勝手に開いてしまいます。openModal()が勝手に動いているようですが、該当のクリックイベントしか呼んでいません。可能性を洗い出してもらえますか?」

返ってきた回答:

  • addEventListener重複して呼ばれている
  • 同じボタンに複数回イベントがバインドされていないか?
  • シングルページアプリではDOMの再生成に伴うイベント消失/二重登録が起こりやすい

③ 原因の特定

function bindModalEvents() {
  document.querySelectorAll('.button').forEach(btn => {
    btn.addEventListener('click', openModal);
  });
}

この関数がページ遷移のたびに呼ばれ、イベントが重複バインドされていました。
その結果、旧ページの状態が生き残っていた

🔧 解決策

対策①:イベントバインド前に remove する

function bindModalEvents() {
  document.querySelectorAll('.button').forEach(btn => {
    btn.removeEventListener('click', openModal); // 既存のバインドを解除
    btn.addEventListener('click', openModal);
  });
}

対策②:once: true オプションの活用(用途次第)

btn.addEventListener('click', openModal, { once: true });

もしご興味あれば、調査時のコメント付きコードや再現手順をまとめたレポジトリを近日中に公開予定です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?