Ashwin
Ashwin

Reputation: 110

Error: Cannot set property 'src' of null

When I try to set the source of a certain element, it returns an error and I have no clue why this is not working. Here is the javascript:

    function playVid() {
  var videoPlayer = document.getElementById("video");
  var mp4VID = document.getElementById("videoSRC");
  var arrOfVid = ["video/video.mp4","video/video1.mp4"]; //, "video/video2.mp4", "video/video3.mp4"];
  var arrLenVID = arrOfVid.length;
  var randomVID = Math.floor((Math.random() * arrLenVID));
  mp4VID.src = arrOfVid[randomVID]; // mp4VIDSRC.src = arrOfVid[randomVID]
  videoPlayer.load();
  videoPlayer.volume = 0;
  videoPlayer.play();
}
playVid();

The HTML part of it is:

<video id="video" autoplay="" style="" muted="">
<source id="videoSRC" src="video/video.mp4" type="video/mp4"> 
    error: unsupported video format
</video>

Here's the error message I'm receiving:

Uncaught TypeError: Cannot set property 'src' of null

Nothing else seems to cross paths with it.

Upvotes: 0

Views: 4402

Answers (2)

bcr666
bcr666

Reputation: 2197

When an HTML page is loaded, the browser attempts to execute things in the top of the page before the page is completely loaded. So if your javascript function call (playVid();) is at the top of the page, it is trying to execute var mp4VID = document.getElementById("videoSRC"); before the videoSRC is loaded. Therefore mp4VID is null, and you can't set a property on a null object. You have two options if this is the case.

1) move the function call to the bottom of the page, just before the closing html tag.

2) Use a framework like jQuery and schedule the function call to execute after the page is loaded $(document).ready(playVid); for example.

#2 is my preferred method:

In my experience, most people don't like when videos start to automatically play.

Upvotes: 2

The Real Fake Admin
The Real Fake Admin

Reputation: 35

You can't set it to a value because mp4VID is a child of video: instead set var mp4VID to equal videoPlyr.children["videoSRC"].

Hope this answered your question :)

Upvotes: 1

Related Questions