I am relatively new to the Gatbsy framework and I am trying to figure out a way to toggle classes on some elements on DOMContentLoaded
or on window.load
, to animate them as soon as the user can see the screen.
This is what I did until now however it doesn't seem very appropriate:
componentDidMount = () => {
if (typeof window === "undefined") return
window.addEventListener("load", this.myEventHandler)
// or
if (typeof document === "undefined") return
document.addEventListener("DOMContentLoaded", this.myEventHandler)
}
Is there a better way of doing this?
Thank you in advance.
The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.
js API file. The file gatsby-browser. js lets you respond to actions within the browser, and wrap your site in additional components. The Gatsby Browser API gives you many options for interacting with the client-side of Gatsby.
I think you should add these event listeners in the gatsby-browser.js
:
// gatsby-browser.js
// ES6
export const onClientEntry = () => {
window.onload = () => { /* do stuff */ }
}
// or commonjs
exports.onClientEntry = () => {
window.onload = () => { /* do stuff */ }
}
You don't have to check for window
there because this file is only run on the client side. Here's the full list of available hooks.
also AFAIK document
doesn't have a ready
event, it's a jQuery
thing. You might be interested in DOMContentLoaded event, though there's some small different between that and jQuery's ready IIRC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With