Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.