TheWardedCoder
TheWardedCoder

Reputation: 99

v-for dynamic video with same id tags creates error

I am currently uploading a video file and using v-for to create video tags with the video's Url. In each tag I have the Id of "myVideo" I know I cannot have two of the same Id on a page but how can I target the correct video otherwise?

here is my code that is dynamically made.

<video @click="playPause" v-if="card.type == 'Video'" class="card__video" :src="card.imageurl[0]" id="myVideo"></video>

the method on click is:

playPause() {
             const myVideo = document.getElementById("myVideo")
             if(myVideo.paused) {
                 myVideo.play()
             } else {
                 myVideo.pause()
             }
        }

I have multiple videos on my page but only the first one plays because it just targets the first video with the id="myVideo"

Upvotes: 1

Views: 27

Answers (1)

Ana Liza Pandac
Ana Liza Pandac

Reputation: 4861

You can use the default event object passed to the function to access the video element.

With this, you can remove the duplicated id attribute that you assigned to your video elements.

<video @click="playPause" v-if="card.type == 'Video'" class="card__video" :src="card.imageurl[0]"></video>
playPause(event) {
  const myVideo = event.target;
  if(myVideo.paused) {
    myVideo.play();
  } else {
    myVideo.pause();
  }
}

See working example

Upvotes: 1

Related Questions