Skip to content

Instantly share code, notes, and snippets.

@gemmadlou
Created February 21, 2018 14:57
Show Gist options
  • Select an option

  • Save gemmadlou/bfd7297ff7e8f485d65bd990b4f625f6 to your computer and use it in GitHub Desktop.

Select an option

Save gemmadlou/bfd7297ff7e8f485d65bd990b4f625f6 to your computer and use it in GitHub Desktop.
My rubbish javascript code
/**
* @todo rewrite so logic is separated out and it's testable
* @todo Properly develop if time allows
*/
export const highlightNav = () => {
let scrollPos = window.scrollY;
let hashLinks = document.querySelectorAll('.js-hash-nav');
Array.from(hashLinks).forEach((link, index) => {
let nextElement = hashLinks[(index + 1)];
let content = document.getElementById(link.hash.replace('#', ''));
let nextContent = nextElement ? document.getElementById(nextElement.hash.replace('#', '')) : false;
if (content == null) {
return;
}
link.classList.remove('active');
let offsetTop = content.offsetTop;
let body = document.querySelector('body');
let offsetBottom = nextContent ? nextContent.offsetTop : body.scrollHeight;
if (index === 0 && scrollPos < offsetTop) {
link.classList.add('active');
} else if (scrollPos > offsetTop && scrollPos < offsetBottom) {
link.classList.add('active');
}
});
};
/**
* @todo Properly develop if time allows
*/
export const selectNavByHash = (window, navSelector = '.js-hash-nav', activeClass = 'active') => {
let hash = window.location.hash;
if (hash === '') {
return;
}
let element = document.querySelector(`a[href="${hash}"]`);
Array.from(document.querySelectorAll(navSelector)).forEach(nav => {
nav.classList.remove(activeClass);
});
if (element === null) {
return;
}
element.classList.add(activeClass);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment