Created
May 15, 2019 16:21
-
-
Save pandauxstudio/1dc706d69e64acaabf9e115c6d06be7d to your computer and use it in GitHub Desktop.
Add scroll animation to anchor links on a page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { render } from 'react-dom'; | |
import { BrowserRouter as Router, Route } from 'react-router-dom'; | |
import { createBrowserHistory } from 'history'; | |
const addScrollAnimation = () => { | |
const anchorLinks = document.querySelectorAll('[href*="#"]'); | |
anchorLinks.forEach((anchorLink) => { | |
anchorLink.addEventListener('click', (e) => { | |
const href = e.target.getAttribute('href'); | |
const hashval = href.substring(href.indexOf('#') + 1); | |
if (e.target.dataset.targetid) { | |
const target = document.querySelector(`#${e.target.dataset.targetid}`); | |
target.scrollIntoView({ | |
behavior: 'smooth', | |
block: 'start', | |
inline: 'end' | |
}); | |
const history = createBrowserHistory(); | |
history.push(`#${hashval}`); | |
e.preventDefault(); | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment