Skip to content

Instantly share code, notes, and snippets.

@Innei
Created August 13, 2020 13:01
Show Gist options
  • Save Innei/4053ab46b97a9669c93cf9c147dffe92 to your computer and use it in GitHub Desktop.
Save Innei/4053ab46b97a9669c93cf9c147dffe92 to your computer and use it in GitHub Desktop.
Animate your url transitions
/*
* @Author: Innei
* @Date: 2020-08-13 19:55:12
* @LastEditTime: 2020-08-13 20:57:59
* @LastEditors: Innei
* @FilePath: /url-animation/index.js
* @Coding with Love
*/
// @ts-check
const allHref = [...document.querySelectorAll('a')]
/**
* @type {number | null}
*/
let timer = null
let once = false
allHref.map(($$) => {
$$.addEventListener('click', (e) => {
e.preventDefault()
const href = $$.getAttribute('href')
if (href.charAt(0) === '#') {
if (timer) {
clearInterval(timer)
}
const uri = '/'.concat(href.slice(1, href.length))
const title = $$.getAttribute('data-title')
const currentTitle = document.title
timer = setInterval(() => {
const beforeUri = encodeURI(
decodeURI(location.pathname).replace(
/<% emojiSequence %>|\p{Emoji_Presentation}|\p{Emoji}\uFE0F|\p{Emoji_Modifier_Base}/gu,
'',
),
)
/**
* @type {string}
*/
const afterUri = uri
// const handler = (event) => {
// clearInterval(timer)
// history.pushState(null, title ?? currentTitle, afterUri)
// event.preventDefault()
// const msg = '地址正在过度, 现在刷新可能出现问题哦'
// event.returnValue = msg
// return msg
// }
console.log(beforeUri === afterUri)
if (beforeUri === afterUri) {
clearInterval(timer)
return history.replaceState(null, title ?? currentTitle, afterUri)
// window.removeEventListener('beforeunload', handler)
}
const isBuild = afterUri.indexOf(beforeUri) > -1
const stepUri = isBuild
? beforeUri.concat(afterUri.charAt(beforeUri.length))
: beforeUri.slice(0, beforeUri.length - 1)
if (!once) {
// window.addEventListener('beforeunload', handler)
history.pushState(null, title ?? currentTitle, afterUri)
}
history.replaceState(
null,
title ?? currentTitle,
`${stepUri}${!isBuild ? `🔨👴` : `🍻`}`,
)
once = true
}, 100)
// history.replaceState(null, title ?? currentTitle, uri)
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment