Matt Jones
Matt Jones

Reputation: 509

JavaScript null reference error

I have a piece of code shown below that is supposed to select the first object in a list of image object. When it runs, about half of the time I am getting an error:

TypeError: Cannot read property of mylist

I realize that this is happening because it is trying to reference an object that has not yet been given a reference to an object. Basically, the page will load, and I want to call this function in JavaScript, however if this code runs before the list is referenced, it errors out. Here is my code snippet:

window.onload = function () {
       try {
            var tnl = $find('mylist');


            tnl.selectFirstItem();
       }
       catch (exception) {
            alert(exception);
       }
}

The

tnl.selectFirstItem()

line is the one throwing the error to the catch block.

So, my question is, is there a way to force it to wait until this object "tnl" has been referenced?

Thanks!

Upvotes: 0

Views: 2250

Answers (2)

Igor
Igor

Reputation: 15893

Here is the "loop" you are asking for. But this is still wrong. If tnl is not assigned after $find('mylist'); returns, it is not going to become assigned later. You likely have error thrown by $find call.

window.onload = function () {
  try {
    var tnl = $find('mylist');

    var timer = setInterval(function() {
      if (tnl) {
        clearInterval(timer); 
        tnl.selectFirstItem();
      }
    }, 1000);

  } catch (exception) {
    alert(exception);
  }
}

Upvotes: 1

Kolby
Kolby

Reputation: 2865

var tnl = $find('mylist');

should be

var tnl = $('#mylist');

assuming mylist is an ID.

You're using find wrong.

First you get your element, then you use it to find a child element. So you could do this:

var container = $('.containerElement');
container.find('#mylist');

Upvotes: 2

Related Questions