javascript - Making JQuery function Plain JS -


hey have following function works great in jquery, many reasons require 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 convert plain js (see below) it's coming following error: typeerror: undefined not 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 trick:

var sounds = document.getelementsbytagname('audio'); /* loop through nodelist - **not** array */ for(var = 0; < sounds.length; i++){     /* item in nodelist. **is** element. */     var sound = sounds.item(i);     /* add event listener here - can add 1 @       * time, though. decided make event separate        * function , attach multiple timers. */     function eventhandler(){         document.title = document.title.replace('\u25b6', '')         if (!sound.paused) {             document.title = '\u25b6 ' + document.title.replace('\u25b6 ', '')             return false;         }     }     sound.addeventlistener('play', eventhandler, false);     sound.addeventlistener('pause', eventhandler, false);     sound.addeventlistener('ended', eventhandler, false); } 

two things: document.getelementsbytagname returns htmlnodelist not array. can looped through because has length property, cannot use foreach(since has function called item, used element @ provided index of nodelist).

secondly, this not refer item in foreach, need pass parameter foreach function can reference (aka array.foreach(function(item){}); item referenced item). said, won't make difference here nodelist not array.

updated

it came me there simple way attach events, amended appropriately.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -