Search code examples
javascripttypescripthtml5-video

Javascript video pause is not a function


So I'm having a little trouble with videos, i have a website and there i have the same video displayed in 3 different pages. The videos are all paused until the user clicks on them to start. The problem is when, i leave a page and the video is just there even if i have clicked on play or pause or haven't done anything at all, the other two, give me an error saying vid.pause is not a function.

This is the HTML part ->

<video id="{{vid?.id}}" src={{vid?.video}} onloadedmetadata="this.paused = true; this.currentTime = 1" (click)="playPause(vid)"> </video>

And the js ->

  playPause(vid) {
    var vid = (<HTMLMediaElement>document.getElementById(vid.id));
    if (vid.paused == true) {
      vid.play();
    } else {
      vid.pause();
      vid.currentTime = 1;
    }
  }

Solution

  • UPDATE:

    One thing to notice is:

    You are passing the vid property to the element and then back to the .ts. This is not good practices.

    Also, you are using variables inside properties the wrong way.

    The best way to do this would be:

    .html file

    <video #myVideo [id]="vid?.id" [src]="vid?.video" onloadedmetadata="this.paused = true; this.currentTime = 1" (click)="playPause(myVideo)"> </video>
    

    .ts file

    playPause(vid: HTMLMediaElement) {
        if (vid.paused == true) {
          vid.play();
        } else {
          vid.pause();
          vid.currentTime = 1;
        }
      }
    

    My guess is you have a difference in your HTML and JS files.

    In your HTML file, you have the video id as vid.id. In your JS file, you are using getElementById, passing the id as vid.video.

    Therefore var vid will be undefined and vid.pause() won't be a function.

    You probably have to use var vid = (<HTMLMediaElement>document.getElementById(vid.id));