Skip to content

Commit f2cd6f7

Browse files
committed
Validate selector before calling scrollIntoView
Fix #4
1 parent 6906b78 commit f2cd6f7

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

index.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/**
22
* Smooth scrolling onClick event handler
33
* @param {string} selector argument will be passed to `querySelector`, usually an HTML id
4+
* @returns {boolean} false if `document.querySelector` doesn't find a match, otherwise true
45
*/
5-
declare const scrollTo: (selector: string) => void;
6+
declare const scrollTo: (selector: string) => boolean;
67
export default scrollTo;

src/index.js

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,28 @@
11
/**
22
* Smooth scrolling onClick event handler
33
* @param {string} selector argument will be passed to `querySelector`, usually an HTML id
4+
* @returns {boolean} false if `document.querySelector` doesn't find a match, otherwise true
45
*/
56
const scrollTo = (selector) => {
6-
document.querySelector(selector).scrollIntoView({
7-
behavior: 'smooth',
8-
block: 'start',
9-
});
7+
const element = document.querySelector(selector);
8+
9+
if (element) {
10+
element.scrollIntoView({
11+
behavior: 'smooth',
12+
block: 'start',
13+
});
14+
15+
return true;
16+
}
17+
18+
if (process.env.NODE_ENV !== 'production') {
19+
console.warn(
20+
"gatsby-plugin-smoothscroll:\n The selector: '%s' wasn't found in the document.\n Make sure you pass in a valid CSS selector string.",
21+
selector
22+
);
23+
}
24+
25+
return false;
1026
};
1127

1228
export default scrollTo;

0 commit comments

Comments
 (0)