File size: 2,187 Bytes
50e8e86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
document.addEventListener('DOMContentLoaded', function () {
  const sections = document.querySelectorAll('section[id]')
  const navItems = document.querySelectorAll('.sidebar .nav-item')
  const sidebar = document.querySelector('.sidebar')
  const footer = document.getElementById('footer')

  document.querySelectorAll('.sidebar a[href^="#"]').forEach((link) => {
    const target = link.getAttribute('href')
    const parentItem = link.closest('.nav-item')
    if (parentItem && target) {
      parentItem.setAttribute('data-target', target)
    }
  })

  function updateActiveLink() {
    let currentSectionId = null

    sections.forEach((section) => {
      const rect = section.getBoundingClientRect()
      if (rect.top <= 100 && rect.bottom >= 50) {
        currentSectionId = section.id
      }
    })

    navItems.forEach((item) => item.classList.remove('active'))

    if (!currentSectionId) return

    const activeItem = document.querySelector(
      `.sidebar .nav-item[data-target="#${currentSectionId}"]`
    )
    if (activeItem) {
      activeItem.classList.add('active')
    }
  }

  function adjustSidebarPosition() {
    if (!sidebar || !footer) return

    const footerRect = footer.getBoundingClientRect()
    const sidebarHeight = sidebar.offsetHeight
    const scrollTop = window.scrollY || document.documentElement.scrollTop

    const footerTop = scrollTop + footerRect.top

    const bodyContainer = document.querySelector('.body-container')
    const bodyBottom = bodyContainer
      ? bodyContainer.offsetTop + bodyContainer.offsetHeight
      : footerTop

    const initialSidebarTop = window.innerHeight * 0.2
    const sidebarBottomOnPage = scrollTop + initialSidebarTop + sidebarHeight

    if (sidebarBottomOnPage >= footerTop - 20) {
      sidebar.style.position = 'absolute'
      sidebar.style.top = `${bodyBottom - sidebarHeight - 20}px`
    } else {
      sidebar.style.position = 'fixed'
      sidebar.style.top = `${20}%`
    }
  }

  window.addEventListener('scroll', () => {
    updateActiveLink()
    adjustSidebarPosition()
  })

  window.addEventListener('resize', adjustSidebarPosition)

  updateActiveLink()
  adjustSidebarPosition()
})