Last active
February 8, 2019 00:23
-
-
Save zaidaldabbagh/787b9eac76299092c478a1e8141809f0 to your computer and use it in GitHub Desktop.
Add scroll animation to anchor links on a page
This file contains hidden or 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