In my react code, I included some jQuery code to make the home page components fade into visibility on scroll. It works fine, but when I navigate to another page like the ‘all posts’ page and then try to scroll, it gives an error saying
Cannot read properties of undefined (reading 'top')
TypeError: Cannot read properties of undefined (reading 'top')
this ‘top’ comes from the method checking the position of the element, if it has scrolled into view, the jQuery in former homepage is running and affecting the new page causing error.
I tried putting conditional statement to check before code execution and a try catch line of code but it isn’t catching this particular error neither is the conditional. How can I fix this? Is there a better way to write the jQuery code to avoid this error? The jQuery Code can be found below.
NB: This error usually goes away anytime I refresh the new page, but it is a bug I feel would affect user experience and needs to be fixed
$(()=>{//jquery to make the homepage components become visible on scroll
try{
$(document).on("scroll", function() {
var pageTop = $(document).scrollTop();//get numerical value of top of page
var pageBottom = pageTop + $(window).height();//get numerical value of bottom of page
var tags = $(".icon-box");//select icon boxes
//this code makes the 'what we offer' icon boxes become visible on scroll
if ($(tags[0]).position().top){
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if ($(tag)?.position().top < pageBottom) {
$(tag).addClass("visible");
} else {
$(tag).removeClass("visible");
}
}}else{console.log('Not on Page')}
});}catch(err){console.log(err)}
});
2
Answers
You can check the length (length is a number of elements with particular selector) of elements which is available on the page.
Example code:
OR
You need to put part of your code in one more IF condition as shown below.
I hope this will be helpful.
Thanks, Jignesh Raval
You can simplify the code a bit but also check if there ARE any such elements before trying to access the first ones position.
I added a nasty element just to induce scroll.