Tristan Navarrete Tristan Navarrete - 1 month ago 17
Javascript Question

Uncaught TypeError: Cannot read property 'id' of null

I'm trying to create an html5 audio player. It's for a radio station, so I need the player to reload the source and start playing from 'currrentTime=0;' when the stream starts again. I get an error in the script though, and i'm not sure why?

My script is run

Error location:

if (player.id == 'paused') {
- I get the error:
' Uncaught TypeError: Cannot read property 'id' of null


HTML:

<audio onplay="checkState()" controls="controls" id="paused" src="http://rmceng.radiomaria.ca:8162/;stream.mp3"></audio>


My JS:

function checkState() {
var player = document.getElementById('player');
var psrc = 'http://rmceng.radiomaria.ca:8162/;stream.mp3';
if (player.id == 'paused') {
player.currentTime = 0;
player.src = psrc;
player.load();
player.play();
document.getElementById('player').id = 'playing';
}
else {
player.pause();
player.src = "";
document.getElementById('player').id = 'paused';
}
}

window.onload = function(){
checkState();
}

Answer

You have no element in your markup that has the id player. So when you tell JS to getElementById, it can't find anything. So the value becomes 'null'. After that you call player.id - this is the same as trying to call the property id of an object that doesn't exist.

To fix: Give your player the attribute id="player" or change the selection call. There are other ways to select elements.

document.getElementById(id_string)
document.getElementsByTagName(tag_name)
document.getElementsByClassName("class_values")
document.getElementsByName("name_value")
document.querySelector(css_selector)
document.querySelectorAll(css_selector)
Comments