7

I have been working on a piece of code that is meant to handle multiple, small video elements on a single webpage but I am having trouble making the multiple progress bars sync with their respective videos.

(Current jsFiddle prototype)

This piece of code $(this).find("progress").attr("value", $("video", this)[0].currentTime); seems to work inside the main function, but when I wrap it in another function with a setTimeout so the progress bar actually animates I get this error:

"Cannot read property 'currentTime' of undefined at function"

I've tried a few variations to see if I could get it working myself but I haven't been able to fix it by throwing code at the wall like I usually do.

Would someone be able to tell me why it's doing this?

GG.
  • 21,083
  • 14
  • 84
  • 130
Kayboy Bebop
  • 95
  • 1
  • 10

2 Answers2

11

In the setTimeout your this is not the main this. So your code doesn't work. To work in the setTimeout, you need to get the this before the setTimeout and the use it.

Example

var that = this;
setTimeout(function(){
 // here use that
},100);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • What if the value of this changes and we want the new value inside the timeout? – Jus10 Mar 28 '17 at 06:28
  • @Jus10 how it will be changed? – Suren Srapyan Mar 28 '17 at 06:32
  • Well let's say you set the value of that to this, then you start a timer and this changes, then the timer runs out and now you're working with an old value that isn't up-to-date. – Jus10 Mar 28 '17 at 06:51
  • @Jus10 can you give an example of how 'this' would change? 'this' refers to the particular instance of that object. – HanifC Feb 22 '20 at 16:59
  • It's old, but I think about this one: showTooltip(e) { e.currentTarget.classList.add('tooltip'); setTimeout(()=>e.currentTarget.classList.remove('tooltip'), 1000); } – Wiktor Kujawa May 22 '22 at 23:48
0

You must change progress max to video duration or total time. and make it value to currenttime . then lets go

$(document).ready(function(){
    var video = $('#YourVideoIDorClass').get(0`);
    video.addEventListener("onplaying", function () {
       progress.val = video.currentTime
    }, false);

})
Morteza Negahi
  • 3,305
  • 8
  • 24
  • 42
  • My current code actually does change the progress bar's `max` and `value` attributes now that I've integrated Suren's answer. Your approach definitely looks more elegant than mine though, so I'll probably save it for when I try and optimize a bit more. Thanks kindly – Kayboy Bebop Dec 14 '16 at 07:08