'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 1:[1]

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));

Solution 2:[2]

The problem for me was that I tried pausing a jQuery object, but that's not possible. You need to pause a DOM element. So I corrected it by converting my jQuery object to a DOM element.

BEFORE:

$("#video").pause();

AFTER / SOLVED:

$("#video)[0].pause();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Web Developer