
How to use IntersectionObserver to detect the position in…
When working with web we often need to animate or reveal html elements by detecting the scroll position. One such example would be to display a container for a state variable and scroll. The IntersectionObserver is a useful interface to achieve such functionality.
01. Using IntersectionObserver
IntersectionObserver has a two main parmeters
let observer = new IntersectionObserver(callback, options);
options = {
root // element for checking root visibility
rootMargin // margins around the root for visibility
threshold // A number of percentage of visibility or an array of points as a percentage. For 100% its 1.0 and for 25% its .25
}
For our example we will use root: null
and root-margins: '0px',
When root is null it will take the browser viewport as the default root. threshold: 0.5
will be used to load the animation when 50% is loaded.
02. Using useCallback with state variables
We need to show the animation only once when the content is showed. For this I will be using a state variable. The state will be set when callback function is triggerred.
const [isFocused, setFocused] = useState(false); const onObserved = useCallback((entries) => { const [entry] = entries; !isFocused && setFocused(entry.isIntersecting); }, []);
Here we have to enclose the callback with useCallback
to ensure the function is initialized once. Unless the removing after effect is over will not be successful as it creates more of the reference.
Here we have taken the first element from the entries array and checked isIntersecting
property to set animating variable as true
03. Using useEffect to register observer
If you can remember we had used root: null
for the observer. But we need to show the content only when this particular view is loaded. For that we can get the outer container ref to a variable and register the observer to it.
export const AnimatedWrapper = () => { const containerRef = useRef(null); // ... return ( <div ref={containerRef}> <AnimatedView isFocused={isFocused} /> </div> ); }
Now to register the observer we will implement useEffect
hook.
useEffect(() => { const observer = new IntersectionObserver(onObserved, { root: null, rootMargin: '0px', threshold: 0.5, }); let current = null; if (containerRef?.current) { current = containerRef.current; observer.observe(current); } return () => { if (current) { observer.unobserve(current); } } }, [containerRef, onObserved]);
This hook will be called when the containerRef
and onObserved
is changed. Also note that the return function will unobserve the observer
when effect is over.
Full implementation code as follows. The isFocused
field is passed to the animated container to make sure that the animation is loaded when the view is focused.
import React, {useRef, useState, useEffect, useCallback} from 'react'; export const AnimatedWrapper = () => { const containerRef = useRef(null); const [isFocused, setFocused] = useState(false); const onObserved = useCallback((entries) => { const [entry] = entries; !isFocused && setFocused(entry.isIntersecting); }, []); useEffect(() => { const observer = new IntersectionObserver(onObserved, { root: null, rootMargin: '0px', threshold: 0.5, }); let current = null; if (containerRef?.current) { current = containerRef.current; observer.observe(current); } return () => { if (current) { observer.unobserve(current); } } }, [containerRef, onObserved]); return ( <div ref={containerRef}> <AnimatedView isFocused={isFocused} /> </div> ); }; export default AnimatedWrapper;
You can find the API document here https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
120 COMMENTS
online cialis Low strength Tadalafil 5mg or less is intended for daily use and works continuously
These treatments are available for treating or curing erectile dysfunction where to buy cialis
online stromectol i had the exact same prob about a week ago bro
Results Primary analysis revealed differences among the groups improvements in scores for the 3 questionnaires P P P P post hoc analysis where to buy lasix water pill
Very interesting info !Perfect just what I was searching for!
Your article is a great resource for anyone seeking information on this topic. The way you organized and presented the information is remarkable.
Great article! I really enjoyed reading it and appreciate the insights you shared.
I really appreciate the different perspectives you presented in this article. It’s refreshing to see different viewpoints.
You made a complex topic sound simple. I appreciate your effort to make this article easy to understand for readers.
Your article is a great resource for anyone looking to learn more about this topic. I appreciate the way you organized the information and presented it in a clear and easy-to-follow manner.
I like how you present the information in an easy to understand and structured way.
Thank you for using your platform to raise awareness about this issue. We need more people like you advocating for change.
I love how you use analogies and metaphors to explain complex ideas. It makes the information much more accessible and memorable.
This is a must-read article for anyone interested in this topic. Your writing is engaging and informative, and your ideas are well-supported with evidence.
Thank you for sharing this fascinating article.
I enjoyed reading your article and learned a lot from it. Keep up the good work!
Hi there! Would you mind if I share your blog with my zynga group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Thanks
happy new year 2024 and.. very infomative article keep posting …. and check out my new website https://www.seotoolsay.com
how to index backlink ? watch this
What i do not understood is in truth how you are not actually a lot more smartlyliked than you may be now You are very intelligent You realize therefore significantly in the case of this topic produced me individually imagine it from numerous numerous angles Its like men and women dont seem to be fascinated until it is one thing to do with Woman gaga Your own stuffs nice All the time care for it up
Your article provides depth and breadth of information, making it a valuable resource for anyone interested in the topic.
This is a fantastic article that provides a fresh perspective on the topic. I appreciate the way you challenge readers to think critically about the issue.
I do not even know how I ended up here but I thought this post was great I dont know who you are but definitely youre going to a famous blogger if you arent already Cheers
Thanks I have just been looking for information about this subject for a long time and yours is the best Ive discovered till now However what in regards to the bottom line Are you certain in regards to the supply
Simply wish to say your article is as amazing The clearness in your post is just nice and i could assume youre an expert on this subject Well with your permission let me to grab your feed to keep updated with forthcoming post Thanks a million and please carry on the gratifying work
Hello i think that i saw you visited my weblog so i came to Return the favore Im trying to find things to improve my web siteI suppose its ok to use some of your ideas
I do agree with all the ideas you have introduced on your post They are very convincing and will definitely work Still the posts are very short for newbies May just you please prolong them a little from subsequent time Thank you for the post
Fantastic site A lot of helpful info here Im sending it to some buddies ans additionally sharing in delicious And naturally thanks on your sweat
I have been browsing online more than three hours today yet I never found any interesting article like yours It is pretty worth enough for me In my view if all website owners and bloggers made good content as you did the internet will be a lot more useful than ever before
I just could not leave your web site before suggesting that I really enjoyed the standard information a person supply to your visitors Is gonna be again steadily in order to check up on new posts
Ny weekly very informative articles or reviews at this time.
Real Estate I do not even understand how I ended up here, but I assumed this publish used to be great
Techno rozen naturally like your web site however you need to take a look at the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth on the other hand I will surely come again again.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Simply Sseven I very delighted to find this internet site on bing, just what I was searching for as well saved to fav
I was recommended this website by my cousin I am not sure whether this post is written by him as nobody else know such detailed about my difficulty You are wonderful Thanks
What i do not realize is in fact how you are no longer actually much more wellfavored than you might be right now Youre very intelligent You recognize thus considerably in relation to this topic made me in my view believe it from numerous numerous angles Its like men and women are not fascinated until it is one thing to do with Lady gaga Your own stuffs excellent All the time handle it up
Mating Press There is definately a lot to find out about this subject. I like all the points you made
Masalqseen I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Isla Moon Awesome! Its genuinely remarkable post, I have got much clear idea regarding from this post . Isla Moon
Your article helped me a lot, is there any more related content? Thanks!
you are in reality a just right webmaster The site loading velocity is incredible It seems that you are doing any unique trick In addition The contents are masterwork you have performed a wonderful task on this topic
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/register?ref=P9L9FQKY
BWER sets the standard for weighbridge excellence in Iraq, offering innovative, reliable systems and dedicated support to ensure optimal performance and client satisfaction.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
certainly like your website but you need to take a look at the spelling on quite a few of your posts Many of them are rife with spelling problems and I find it very troublesome to inform the reality nevertheless I will definitely come back again
fueuuy
Noodlemagazine I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will
Nice blog here Also your site loads up fast What host are you using Can I get your affiliate link to your host I wish my web site loaded up as quickly as yours lol
Noodlemagazine naturally like your web site however you need to take a look at the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth on the other hand I will surely come again again.
I believe that avoiding processed foods is the first step for you to lose weight. They may taste beneficial, but processed foods have very little nutritional value, making you try to eat more simply to have enough energy to get throughout the day. In case you are constantly eating these foods, moving over to cereals and other complex carbohydrates will make you to have more vitality while having less. Thanks alot : ) for your blog post.
Attractive section of content I just stumbled upon your blog and in accession capital to assert that I get actually enjoyed account your blog posts Anyway I will be subscribing to your augment and even I achievement you access consistently fast
Interesting blog post. The things i would like to contribute is that pc memory ought to be purchased should your computer can’t cope with that which you do along with it. One can set up two good old ram boards having 1GB each, in particular, but not certainly one of 1GB and one having 2GB. One should always check the manufacturer’s documentation for the PC to make certain what type of memory is essential.
The Best Premium IPTV Service WorldWide!
UID_36274208###
Ini dia info viral link berita dana terkini di indonesia !
UID_74853715###
Berita terbaru Jmarble Race yang mudah dimainkan
Jmarble Race gampang cuan
Jmarble Race bisa dapet milyaran
Jmarble Race modal sedikit
Jmarble Race dapet cuan banyak.
It is really a nice and helpful piece of information. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.
UID_72942561###
Berita Hot! 🔥🔥 Isa Rachmatarwata Tersangka Kasus Jiwasraya Buntut kerugian negara hingga 16,8 Triliun! 😲😲
UID_53550706###
Berita terbaru! 🔥 Isa Rachmatarwata Ditahan Kejagung dalam kasus Jiwasraya. 🚔👮♂️
UID_57092237###
Berita gembira! 🎉 Pasokan Gas 3 Kg di Kramat Jati Kembali Normal 🎊 Siap-siap belanja gas, ya! 💪🔥
UID_72339950###
Heboh! 📣🔥 Unjuk Rasa di Polda Jatim 📢 Menuduh Jokowi Terlibat Korupsi! 😱🔍
UID_27764099###
Ini yang di ganti >>> “Bingung Kenapa 😕❓” Federasi Sepak Bola Pakistan Disanksi FIFA “Baca Penyebabnya Disini! 🧐🔍”
UID_74743238###
Ini dia! 🎉🎉 ASN BKN Ubah Pola Kerja yang baru dan efisien! 🎉🎉.
UID_83344528###
Inilah 🎉🎉 Pupuk Inovatif Kebun Riset Kujang yang bikin Wamen BUMN bangga! 💪🏻🇮🇩
I loved as much as you will receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an edginess over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.
Some really great content on this website, thank you for contribution. “A religious awakening which does not awaken the sleeper to love has roused him in vain.” by Jessamyn West.
UID_25978847###
situs terbaik hanya di slot gacor agentotoplay
UID_95859078###
Baru-baru ini, para pemain Mahjong Wins 3 dikejutkan dengan bocoran RTP yang diklaim bisa meningkatkan peluang kemenangan secara signifikan. Banyak yang percaya bahwa informasi ini membantu mereka mendapatkan hasil yang lebih konsisten dalam permainan. Jika Anda ingin tahu lebih lanjut, cek bocoran RTP Mahjong Wins 3 hari ini dan lihat apakah strategi ini benar-benar efektif.
UID_57331425###
Skandal terbaru mengguncang komunitas pecinta game slot setelah seorang admin terkenal, Rachel, dikabarkan tertangkap membocorkan pola kemenangan Gate of Olympus. Banyak yang bertanya-tanya apakah informasi ini benar-benar akurat atau hanya sekadar rumor yang beredar di kalangan pemain. Simak lebih lanjut detailnya dalam artikel admin Rachel tertangkap bocorkan pola Gate of Olympus.
UID_17136916###
Kisah inspiratif datang dari seorang tukang ojek online asal Tangerang yang berhasil membawa pulang hadiah fantastis setelah bermain Mahjong Ways 2. Dengan modal kecil, ia sukses mengubah nasibnya dan meraih kemenangan besar senilai 200 juta rupiah. Penasaran bagaimana caranya? Simak kisah lengkapnya di artikel tukang ojek online menang 200 juta dari Mahjong Ways 2.
UID_87427935###
Cek yuk! 🚍👮♂️Operasi Keselamatan 2025 Polres Ciamis Siapa tahu bus favoritmu jadi sasaran! 😱👍
UID_18563832###
Ini yang di ganti >>> Yuk, ketahui lebih lanjut tentang Syarat Gabung OECD dan Pentingnya Ratifikasi Konvensi Antisuap di sini! 🕵️♀️🔎📚.
UID_83003169###
Kenalan yuk! 🤝 Dengan guru inspiratif ini, Guru Dede Sulaeman yang mengajarkan cara merapikan pakaian di kelasnya. 👕👚🎓
UID_97211224###
Yuk, sehat bersama! 👨⚕️👩⚕️ Cek kondisi tubuh kamu di Program Cek Kesehatan Gratis sekarang juga! 💉🌡️ Selalu jaga kesehatan, ya! 🏥💖
You are my intake , I have few web logs and occasionally run out from to brand.I conceive this website contains some really wonderful info for everyone. “Drunkenness is temporary suicide.” by Bertrand Russell.
What i do not understood is if truth be told how you are no longer really a lot more smartly-favored than you might be now. You are so intelligent. You realize thus significantly when it comes to this matter, made me in my view imagine it from a lot of various angles. Its like men and women don’t seem to be fascinated unless it is one thing to accomplish with Girl gaga! Your own stuffs great. Always deal with it up!
V8907e6U6b8
nafuDih7g8W
h6vXjIaA7ts
4WCTUrWDDUh
SzKH90bLxWm
T2Cdx0KBS6G
enzrypKvZpQ
4C2FZ6Zf074
PG6uaTDsrOq
WuK59FYuWVR
FeO4rLLEVft
YNbPsm305DC
eilFwCVbtPg
t0UkQEFUI5x
P2wc5ZcGpRf
Kbp2cL0wBlv
Sq9jqCMkPkY
MYXjT8MrGAW
mLtAjua7Qj6
aurIp1wtyHN
jONM9pUI8hB
BwiZT338BJv
46XIJv2jKxc
76szFHTU79R
lFp5bYF0slK
J1GoMwJDfJC
8Ef4czBmQwN
5L64HNBPsJV
ZUe3CwN236w
5suDAf7Ee7P
1HI79aDvsFd
4sbTOVWMPJE
yOhzlYBKZuY
Heb7dKk2NiY
SWwWfhN4qSR
Your article helped me a lot, is there any more related content? Thanks!
Puraburn I really like reading through a post that can make men and women think. Also, thank you for allowing me to comment!
jzywg9
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.