Cannot read property `left` of `undefined` in jQuery?

I am trying to check div come on viewport or not, but I am getting this error:

Cannot read property left of undefined

On scroll event, I am checking which div present in the viewport like so:

( "#container" ).scroll(function() {
      console.log('scrlling');
      $.each( $('#container>div'), function(i, left) {
           console.log(i);
           var msid= $(left).attr('data-msid');
           console.log($(left).attr('data-msid'));
           console.log($(left['data-msid='+msid]).isOnScreen())

          })
    });

here is my code https://plnkr.co/edit/Du5J120AIkNqnnpR30le?p=preview

Answers 1

  • The problem is this statement:

    console.log($(left['data-msid='+msid]).isOnScreen())
    

    Instead of filtering $(left) to make sure it has a data-msid of msid, you are running a dynamic property access on left (due to the square bracket notation). Since left is a DOM node, it does not have any property beginning with data-msid= and so the property access returns undefined. Thus, your code is run as something like this:

    console.log($(undefined).isOnScreen())
    

    I am guessing that isOnScreen() checks a left property at some point, and since the only thing that was passed to jQuery was undefined it is not hard to imagine an error being thrown here eventually.

    The Updated Code:

    $("#container").scroll(function() {
      console.log('scrolling');
      $('#container > div').each(function (i, left) {
        console.log(i);
        var msid = $(left).attr('data-msid');
        console.log(msid);
        console.log($(left).isOnScreen());
      })
    });
    

Related Articles