function debounce(func, wait) {
    let timeout;
    return function() {
      const context = this, args = arguments;
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(context, args), wait);
    };
  }

window.addEventListener('scroll', debounce(() => {
    document.querySelectorAll('.c').forEach(waypoint => {
        if (waypoint.offsetTop <= window.scrollY + 150) { 
            document.getElementById('currentChapter').textContent = " " + waypoint.id.slice(1);
        }
    });
}, 100));


document.addEventListener('click', function(event) {
    const menu = document.querySelector('.menu');
    const menuCheckbox = document.querySelector('.menu-checkbox');
    if(event.target.matches('.menu-checkbox') || event.target.matches('.menu-toggle')) {
        return
    }

    if (menuCheckbox.checked) {
        if (!menu.contains(event.target) || event.target.matches('.menu a')) {
            menuCheckbox.checked = false;
        }
    }
});