Skip to content

Instantly share code, notes, and snippets.

@zaidaldabbagh
Last active February 8, 2019 00:23
Show Gist options
  • Save zaidaldabbagh/787b9eac76299092c478a1e8141809f0 to your computer and use it in GitHub Desktop.
Save zaidaldabbagh/787b9eac76299092c478a1e8141809f0 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