简体   繁体   中英

execute function on URL hash change that isn't detected by window.onhashchange

I am using xaringan slides; xaringan is based on remark.js. I want to implement a Javascript function that triggers on every slide change. (The function could be anything; in my case, it scrolls "presenter notes" to the top of their div upon a slide change.)

remark.js slide decks are HTML files. In the URL for the file, each slide is represented by the number after the hash mark: you have "mySlides.html#1", "mySlides.html#2", and so on. So it might seem that I can implement the behavior that I want with window.onhashchange :

function myFunc() {
  console.log("Triggered myFunc()!")
}
window.onhashchange = myFunc;  

This code works when a user changes slides by using the "back" or "forward" buttons in the browser. It also works when he types the change into the address bar. For example, it works if he sees "mySlides.html#1" in the address bar, deletes the "1", replaces it with a "2", and presses Enter.

But no one changes slides in those ways. Instead, they change slides by swiping on their tablets, scrolling their mouse wheels, or pressing the left- and right-arrow keys. All of these shortcuts change the slide and the hash that appears in the address bar. But none of them trigger window.onhashchange .

Is there a way to execute a function whenever the hash in the URL changes, even when it isn't changed by typing in the address bar or by clicking the "back" button? For example, location.hash changes every time that a user changes from one slide to another -- is there a way to listen for changes to location.hash ?

Per charlietfl's comment, remark.js comes with slide-change events that are easy to trigger:

function myFunc() {
  console.log("Triggered myFunc()!")
}
slideshow.on('showSlide', myFunc);

is all that one needs to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM