PageSourceSearch

https://uwsc.jp/wp-content/themes/codium-extend-child/js/features/anchor-back.js

js uwsc.jp collected 2026-10-01 15:54:33 UTC 2,171 bytes, 98 lines download raw bytes

1export function initAnchorBack() {
2  const stackKey = 'anchorBackStack';
3
4  const getStack = () => {
5    try {
6      return JSON.parse(sessionStorage.getItem(stackKey) || '[]');
7    } catch {
8      return [];
9    }
10  };
11
12  const setStack = (s) => {
13    sessionStorage.setItem(stackKey, JSON.stringify(s));
14  };
15
16  const pushPos = (pos) => {
17    const s = getStack();
18    s.push(pos);
19    setStack(s);
20  };
21
22  const popPos = () => {
23    const s = getStack();
24    const pos = s.pop();
25    setStack(s);
26    return pos;
27  };
28
29  const btn = document.getElementById('back-anchor');
30
31  const showButton = () => {
32    if (!btn) return;
33    btn.classList.remove('hidden');
34    btn.setAttribute('aria-hidden', 'false');
35  };
36
37  const hideButton = () => {
38    if (!btn) return;
39    btn.classList.add('hidden');
40    btn.setAttribute('aria-hidden', 'true');
41  };
42
43  // アンカーリンククリック時:移動前のスクロール位置を保存
44  document.addEventListener(
45    'click',
46    (e) => {
47      const a = e.target.closest('a[href^="#"]');
48      if (!a) return;
49
50      const href = a.getAttribute('href');
51      if (!href || href === '#') return;
52
53      const pos = {
54        x: window.scrollX,
55        y: window.scrollY,
56        time: Date.now()
57      };
58
59      pushPos(pos);
60    },
61    { passive: true }
62  );
63
64  // ハッシュ変更後:戻るボタンを表示
65  window.addEventListener('hashchange', () => {
66    const s = getStack();
67    if (s.length > 0) showButton();
68    else hideButton();
69  });
70
71  // 戻るボタン押下
72  if (btn) {
73    btn.addEventListener('click', (e) => {
74      e.preventDefault();
75
76      const prev = popPos();
77      if (!prev) {
78        hideButton();
79        return;
80      }
81
82      window.scrollTo({
83        left: prev.x,
84        top: prev.y,
85        behavior: 'smooth'
86      });
87
88      if (getStack().length === 0) hideButton();
89    });
90  }
91
92  // ページロード時の初期状態
93  window.addEventListener('load', () => {
94    const s = getStack();
95    if (location.hash && s.length > 0) showButton();
96    else hideButton();
97  });
98}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.