T.XL T.XL - 1 year ago 68
Javascript Question

HTML5 video with javascript - syntax confusion

I am trying to make a custom video. I can get my functions to work. However when I have two event listeners together:

e.g. video.ontimeupdate

only the bottom one will operate when I play the video. Is there a better way for me to write my functions, so that I do not have this problem?

Event listeners

time.addEventListener("timeupdate", currentTime, true);
video.ontimeupdate = function() {currentTime()};

seek.addEventListener("timeupdate", progressBarUpdate, true);
video.ontimeupdate = function() {progressBarUpdate()};


Function code example

// Updating the progress bar function

function progressBarUpdate() {

// Calculate the progress bar value
var value = (100 / video.duration) * video.currentTime;
// Update the progress bar value
seek.value = value;
}

Answer Source

There are two different mechanisms for registering event handlers:

time.addEventListener("timeupdate", currentTime, true);
video.ontimeupdate = function() {currentTime()};

When you use a property (ontimeupdate) and you give it a value, that value will be overwritten when you set that property to another value.

So, when you do this:

video.ontimeupdate = function() {currentTime()};

It gets overridden by this later:

video.ontimeupdate = function() {progressBarUpdate()};

To prevent this from happening, use the more modern W3C DOM Level 2 event handling model that uses addEventListener

 video.addEventListener("timeupdate", currentTime);
 video.addEventListener("timeupdate", progressBarUpdate);

This will register both functions as callbacks to the timeupdate event.

Additionally, there is a third parameter for addEventListener (a boolean) which indicates whether you want the callback to fire during the capture phase (true) or the bubbling phase (false). It is a bit unusual to need the capture phase, so you may want to modify your existing true values to false or just omit the third argument as false is the default.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download