スマホでモーダルメニューを開閉する時にアコーディオンをリセット(閉じ状態)する

Filed under: JavaScript — kdcs @ 26年3月31日 火曜日

モーダルメニューの中でアコーディオンを使う時、アコーディオンを開いた状態でメニューを閉じて再度モーダルメニューを開いたときにアコーディオンを閉じた状態にしたいので、モーダルメニュー開閉にアコーディオンのリセットを組み込んだコード。

var trigger = document.querySelector('.globalMenu');
var closeButtons = document.querySelectorAll('.closeButton');
var body = document.body;
var modal = document.getElementById('globalNavArea');
let scrollPosition = 0;

// ★ アコーディオンを閉じる処理(チラつき防止付き)
function resetAccordion() {
  const menu = document.querySelector('.gnBrandMenu');
  const btn = document.querySelector('.gnBrandBtn');

  if (!menu || !btn) return;

  // ★ transition を一時的に無効化(チラつき防止)
  menu.style.transition = 'none';

  // アコーディオンを閉じる
  menu.classList.remove('open');
  btn.classList.remove('active');
  menu.style.maxHeight = null;

  // ★ 次のフレームで transition を元に戻す
  requestAnimationFrame(() => {
    menu.style.transition = '';
  });
}

// モーダルを閉じる処理
function closeModal() {
  trigger.classList.remove('is-active');
  body.classList.remove('is-nav-opened');
  body.classList.add('is-nav-close');

  body.style.top = '';
  window.scrollTo(0, scrollPosition);

  // ★ モーダルを閉じたらアコーディオンも閉じる(チラつきなし)
  resetAccordion();
}

// モーダルを開く処理
function openModal() {
  scrollPosition = window.scrollY;

  trigger.classList.add('is-active');

  if (body.classList.contains('is-nav-close')) {
    body.classList.remove('is-nav-close');
  }

  body.classList.add('is-nav-opened');

  body.style.top = `-${scrollPosition}px`;
  modal.scrollTop = 0;
}

// トリガークリック
trigger.addEventListener('click', function () {
  if (body.classList.contains('is-nav-opened')) {
    closeModal();
  } else {
    openModal();
  }
});

// closeButton クリックでも閉じる
closeButtons.forEach(btn => {
  btn.addEventListener('click', closeModal);
});

アコーディオンをモーダルメニューの中で使わないときのコード

var trigger = document.querySelector('.globalMenu');
var closeButtons = document.querySelectorAll('.closeButton');
var body = document.body;
var modal = document.getElementById('globalNavArea');
let scrollPosition = 0;

// モーダルを閉じる処理
function closeModal() {
  trigger.classList.remove('is-active');
  body.classList.remove('is-nav-opened');
  body.classList.add('is-nav-close');

  body.style.top = '';
  window.scrollTo(0, scrollPosition);
}

// モーダルを開く処理
function openModal() {
  scrollPosition = window.scrollY;

  trigger.classList.add('is-active');

  if (body.classList.contains('is-nav-close')) {
    body.classList.remove('is-nav-close');
  }

  body.classList.add('is-nav-opened');

  body.style.top = `-${scrollPosition}px`;
  modal.scrollTop = 0;
}

// トリガークリック
trigger.addEventListener('click', function () {
  if (body.classList.contains('is-nav-opened')) {
    closeModal();
  } else {
    openModal();
  }
});

// closeButton クリックでも閉じる
closeButtons.forEach(btn => {
  btn.addEventListener('click', closeModal);
});

サイト内検索

カテゴリー

最近の投稿

« |スマホでモーダルメニューを開閉する時にアコーディオンをリセット(閉じ状態)する| »
↑上に戻る