skip to Main Content

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


  1. var tags = $(".icon-box");//select icon boxes
    
    console.log("Number of icon boxes : " + $(tags).length);
    
    if($(tags).length) {
     console.log('Icon boxes are available on the page.');
    } else {
     console.log('No Icon boxes are available on the page.');
    }
    .icon-box {
     padding: 1rem;
     background: #CCC;
     margin: 1rem;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    
    
    <div class="icon-box">Icon 1</div>
    <div class="icon-box">Icon 2</div>
    <div class="icon-box">Icon 3</div>

    You can check the length (length is a number of elements with particular selector) of elements which is available on the page.

    Example code:

    if ( $( "#myDiv" ).length ) {
        $( "#myDiv" ).show();
    }
    

    OR

    if ( $( "#myDiv" ).length > 0 ) {
        $( "#myDiv" ).show();
    }
    

    You need to put part of your code in one more IF condition as shown below.

    if ($(tags).length) {
        //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') }
    

    I hope this will be helpful.

    Thanks, Jignesh Raval

    Login or Signup to reply.
  2. 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.

    var didOne = false;
    $(() => {
      try {
        $(document).on("scroll", function() {
          const pageTop = $(document).scrollTop();
          const pageBottom = pageTop + $(window).height();
          const tags = $(".icon-box");
          const isONTop = $(tags).length && $(tags[0]).position().top;
          if (isONTop) {
            tags.forEach(function() {
              const tag = this;
              $(tag).toggleClass("visible", isONTop);
            });
          }
          if (!$(tags).length && !didOne) {
            didOne = true; // avoid excess loggin
            console.log('No tags on Page');
          }
        });
      } catch (err) {
        console.log(err)
      }
    });
    .bigger-me {
      border: solid 1px #00ff00;
      padding: 300px;
      background-color: #00ff0020;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="bigger-me">Here we are today is the best day of the day!</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search