Skip to content

Commit

Permalink
Validate selector before calling scrollIntoView
Browse files Browse the repository at this point in the history
Fix #4
  • Loading branch information
freddydumont committed Mar 10, 2020
1 parent 6906b78 commit f2cd6f7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
3 changes: 2 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* Smooth scrolling onClick event handler
* @param {string} selector argument will be passed to `querySelector`, usually an HTML id
* @returns {boolean} false if `document.querySelector` doesn't find a match, otherwise true
*/
declare const scrollTo: (selector: string) => void;
declare const scrollTo: (selector: string) => boolean;
export default scrollTo;
24 changes: 20 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
/**
* Smooth scrolling onClick event handler
* @param {string} selector argument will be passed to `querySelector`, usually an HTML id
* @returns {boolean} false if `document.querySelector` doesn't find a match, otherwise true
*/
const scrollTo = (selector) => {
document.querySelector(selector).scrollIntoView({
behavior: 'smooth',
block: 'start',
});
const element = document.querySelector(selector);

if (element) {
element.scrollIntoView({
behavior: 'smooth',
block: 'start',
});

return true;
}

if (process.env.NODE_ENV !== 'production') {
console.warn(
"gatsby-plugin-smoothscroll:\n The selector: '%s' wasn't found in the document.\n Make sure you pass in a valid CSS selector string.",
selector
);
}

return false;
};

export default scrollTo;

0 comments on commit f2cd6f7

Please sign in to comment.