Skip to content

Instantly share code, notes, and snippets.

@kamilogorek
Created October 16, 2018 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamilogorek/e102d9c8422bc2724889d00054dfbaba to your computer and use it in GitHub Desktop.
Save kamilogorek/e102d9c8422bc2724889d00054dfbaba to your computer and use it in GitHub Desktop.
const entrySelector = "#itemsStream > .entry";
const entries = document.querySelectorAll(entrySelector);
const outlineStyle = "2px solid rgba(108, 176, 221, 0.8)";
const activeClassName = "vimLikeActive";
document.addEventListener("keypress", evt => {
if (document.activeElement !== document.body) return;
if (evt.key === "j") return down();
if (evt.key === "k") return up();
});
function down() {
const activeEntry = document.querySelector(`${entrySelector}.${activeClassName}`);
const nextEntry =
!activeEntry || activeEntry === entries[entries.length - 1] ? entries[0] : activeEntry.nextElementSibling;
toggle(activeEntry, nextEntry);
}
function up() {
const activeEntry = document.querySelector(`${entrySelector}.${activeClassName}`);
let nextEntry =
!activeEntry || activeEntry === entries[0] ? entries[entries.length - 1] : activeEntry.previousElementSibling;
toggle(activeEntry, nextEntry);
}
function toggle(active, next) {
if (active) {
active.classList.remove(activeClassName);
active.style.outline = null;
}
if (next) {
next.classList.add(activeClassName);
next.style.outline = outlineStyle;
window.scrollBy(0, next.getBoundingClientRect().y - 8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment