Hey I have the following function which works great in JQuery, but for many reasons I require it in plain JS.
$('audio').on("play pause ended", function () {
document.title = document.title.replace("\u25B6", "")
$("audio").each(function (index) {
if (!this.paused) {
document.title = "\u25B6 " + document.title.replace("\u25B6 ", "")
return false;
}
})
});
I've attempted to convert it to plain JS (see below) however it's just coming up with the following error: TypeError: undefined is not a function (evaluating 'sound.addEventListener')
var sound = document.getElementsByTagName('audio');
sound.addEventListener('play pause ended', function () {
document.title = document.title.replace('\u25B6', '')
sound.each(function (index) {
if (!this.paused) {
document.title = '\u25B6 ' + document.title.replace('\u25B6 ', '')
return false;
}
})
});
The following should do the trick:
Two things:
document.getElementsByTagName
returns an HTMLNodeList which is not an array. It can be looped through because it has a length property, but it cannot use theforEach
(since it also has a function calleditem
, which is used to get the element at the provided index of the nodelist).Secondly,
this
does not refer to your item in aforEach
, you need to pass a parameter to yourforEach
function that you can reference (akaarray.forEach(function(item){});
where your item would be referenced byitem
). But like I said, that won't make a difference here as anodeList
is not an array.Updated
It just came to me that there is a simple way to attach all events, so I amended it appropriately.