How can I make a function in Javascript global for my html

First, I appreciate any direction given ... Let me preface this by saying: I am learning Javascript and HTML.

My problem is that I am trying to call my function to update the sound time as follows:

<audio id="track" preload="auto" type="audio/mpeg" ontimeupdate="displayTime(this)">
            <source src="mp3/mysong.mp3" type="audio/mpeg">
            Unsupported audio format!
        </audio>

My function is in the IFFE Javascript function:

$(document).ready(function () {
 ... /*Global Variables*/

 ...

 function displayTime(event) {

            sec = Math.floor(event.duration);
            min = Math.floor(sec / 60);
            min = min >= 10 ? min : '0' + min;
            sec = Math.floor(sec % 60);
            sec = sec >= 10 ? sec : '0' + sec;


            ct_sec = Math.floor(event.currentTime);
            ct_min = Math.floor(ct_sec / 60);
            ct_min = ct_min >= 10 ? ct_min : '0' + ct_min;
            ct_sec = Math.floor(ct_sec % 60);
            ct_sec = ct_sec >= 10 ? ct_sec : '0' + ct_sec;


            document.getElementById('ticker').innerHTML = ct_min + ":" + ct_sec + "-" + min + ":" + sec;

        }



});

Can anyone advise why I get the error displayTime function (this) is not defined? I also tried using window.myFunction to try to make it global for dom ... to no avail.

+4
source share
3 answers

because it is not visible outside the scope.

window.displayTime = displayTime;
+5

document.ready . , , ​​ , , window..

$(document).ready(function () {
 ... /*Global Variables*/
window.displayTime = function (event) { ... }
});

:

<button onclick="window.displayTime()">test</button>
+1

As an alternative to creating a global function, you can also attach an event listener via JavaScript as follows:

$('#track').on('timeupdate', displayTime);
0
source

Source: https://habr.com/ru/post/1675529/


All Articles