Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  69] [ 1]  / answers: 1 / hits: 17506  / 8 Years ago, tue, october 25, 2016, 12:00:00

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

More From » html

 Answers
38

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)

[#60279] Sunday, October 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;