Skip to content

Instantly share code, notes, and snippets.

@linuskmr
Created December 27, 2022 12:43
Show Gist options
  • Save linuskmr/f3150949013e5ea1a22adc3f7b03b361 to your computer and use it in GitHub Desktop.
Save linuskmr/f3150949013e5ea1a22adc3f7b03b361 to your computer and use it in GitHub Desktop.
Make a navigable presentation from a HTML page
const sections = document.getElementsByTagName("section");
let currentSectionIndex = 0
// Add style
const style = `
section {
padding: 10px 0;
height: 100vh;
}
`
let styleElement = document.createElement("style")
styleElement.innerText = style
document.head.appendChild(styleElement)
/**
* Scrolls to section with the number `index`.
*/
function scrollToSection(index) {
sections[index].scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"})
}
/**
* Sets `currentSectionIndex` to the new value provided in `index` and scrolls to this section.
*/
function setCurrentSectionIndex(index) {
// Clamp index
if (index < 0) {
index = 0
} else if (index >= sections.length) {
index = sections.length - 1
}
currentSectionIndex = index
scrollToSection(currentSectionIndex)
}
// Go one slide forward when the users presses ->
document.addEventListener('keyup', (e) => {
if (e.code != 'ArrowRight') {
return
}
setCurrentSectionIndex(currentSectionIndex + 1)
})
// Go one slide forward when the users presses <-
document.addEventListener('keyup', (e) => {
if (e.code != 'ArrowLeft') {
return
}
setCurrentSectionIndex(currentSectionIndex - 1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment