0

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!

0

2 Answers 2

2
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');
Sign up to request clarification or add additional context in comments.

8 Comments

No, I am referencing an object created in HTML with ID="mylist" that's not the issue.
It works about half the time as it is. Trust me it is not the issue.
then you have other issues.Actually, it looks like you're not providing the right code. The error is saying the variable mylist is null. Where is that variable being set at?
What is selectFirstItem()? I answered prematurely because you haven't provided us the right information on your project. What kind of javascript library are you using?
Basically, that is all irrelevant. I guess I should have worded my question better. Really what I need to know if how can I force my Javascript to loop at the line tnl.selectFirstItem(); until the tnl has been initialized?
|
1

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);
  }
}

2 Comments

@MattJones - beats me
Read comment I posted on other answer provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.