views:

151

answers:

3

I load everything on my page. At the end, I have this script.

<script type="text/javascript">loadNewVideo('u1zgFlCw8Aw',0)</script>

It doesn't work. But if I substitute it with this, it works.:

<input type="submit" onclick="loadNewVideo('u1zgFlCw8Aw',0);" >

In the .JS file, this is the function:

function loadNewVideo(id, startSeconds) {
            alert('In-the-function');
          if (ytplayer) {
            alert('Found-ytplayer');
            ytplayer.loadVideoById(id, parseInt(startSeconds));
          }
        }

Apparently, "ytplayer" is false in the first one!??

+9  A: 

I don't know what ytplayer is, but I imagine this problem has something to do with the DOM not being fully loaded. Have you tried this?

<script type="text/javascript">
$(document).ready(function() {
  loadNewVideo('u1zgFlCw8Aw', 0);
});
</script>

edit: If this doesn't work, you will have to give us more information. As Tim and Peter asked you in comments to your question, can you tell us where ytplayer is defined and what it is? I'm assuming it stands for YouTube Player, maybe it's being loaded/defined after you were calling loadNewVideo?

For example, if the code snippet above is above the part where ytplayer is defined in your document, this would still be called before ytplayer is loaded, depending on how you're loading it. As I said, please supply some more information.

Aistina
Indeed you are correct; javascript runs as soon as it's read, so you need to make sure anything you want is declared about the script you're running, or (better still) do everything in the 'load' event (as you demonstrate) :)
Noon Silk
@silky: note, ready != load
Tim Büthe
This doesn't work. I've tried document.ready in Jquery.
TIMEX
+4  A: 

I would say this is because the DOM hasn't totally loaded at that stage. You want to hook the body onLoad event, or use jQuery to get the $(document).ready() hook.

Paddy
+4  A: 

I don't have an answer, but perhaps this will help you figure out when the ytplayer component is ready for use:

var startTimer = new Date().getTime();
function ytplayerReadyCheck() {
  var ready = !!ytplayer;
  if (!ready) {
    window.setTimeout(ytplayerReadyCheck,50);
  }
  else {
    var endTimer = new Date().getTime();
    alert('ytplayer is now ready!\n\nWe waited '+(endTimer-startTimer)+' milliseconds for it');
    loadNewVideo('u1zgFlCw8Aw', 0);
  }
}
ytplayerReadyCheck();

Of course, this is scarcely replacement for figuring out where ytplayer is defined in the first place! Perhaps it's defined in a .js file that's dynamically loaded after the document has loaded?

I'd highly recommend getting hold of Firebug so you can more easily debug this kind of thing.

brownstone
Correct. It takes some time before ytplayer loads. Therefore, I put a setTimeout before calling that loadNewVideo function! and then it works.
TIMEX