Skip to content

Instantly share code, notes, and snippets.

@pandauxstudio
Created May 15, 2019 16:21
Show Gist options
  • Save pandauxstudio/1dc706d69e64acaabf9e115c6d06be7d to your computer and use it in GitHub Desktop.
Save pandauxstudio/1dc706d69e64acaabf9e115c6d06be7d to your computer and use it in GitHub Desktop.
Add scroll animation to anchor links on a page
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