Retrieving properties from video element following webpage loading

I am trying to access the 'currentSrc' value from a video object in my code. Here is what I have:

mounted: function () {
    this.$nextTick(function () {
      console.log(document.getElementById('video').currentSrc)
    });
  },

Despite my efforts, all I get is an <empty string>. It's baffling because when I try this:

mounted: function () {
    this.$nextTick(function () {
      console.log(document.getElementById('video'))
    });
  },

I see the correct object with the currentSrc attribute in the console.

I've tried using created(), refs, changing element key values to trigger a re-render, and even using timeouts, but I always end up with an <empty string>. Additionally, trying to use @load on the video element doesn't seem to work at all.

Is there a way to access object values immediately after the page is rendered?

Answer №1

When you look at the initial code snippet, it's clear that <video>.currentSrc is not set when you try to log it because the video loads asynchronously. In contrast, the second snippet simply logs the <video> element itself, and the browser console automatically updates on change, resulting in seeing currentSrc populated.

Prior to accessing any data properties, such as currentSrc, the <video> element must first load the video metadata from its source. This process triggers a loadedmetadata event. To listen for this event in your mounted hook:

export default {
  mounted: function() {
    this.$nextTick(() => {
      const video = document.getElementById('video')
      video.addEventListener("loadedmetadata", function() {
        console.log('currentSrc', video.currentSrc);
      });
    });
  }
}

In case your site possibly has more than one <video> element with an id of "video" (e.g., multiple Vue components on the page containing this <video>), it would be more appropriate to obtain a reference to the intended element using a template ref:

<template>
  <video ref="myVideo"></video>
</template>

<script>
export default {
  mounted: function() {
    this.$nextTick(() => { 
      this.$refs.myVideo.addEventListener("loadedmetadata", () => {
        console.log('currentSrc', this.$refs.myVideo.currentSrc);
      });
    });
  }
}
</script>

Check out demo 1

If your goal is solely to add an event listener, you can use the v-on directive in the template (e.g., v-on:loadedmetadata="METHOD" or @loadedmetadata="METHOD" shorthand):

<template>
  <video ref="myVideo" @loadedmetadata="logCurrentSrc"></video>
</template>

<script>
export default {
  methods: {
    logCurrentSrc() {
      console.log('currentSrc', this.$refs.myVideo.currentSrc);
    }
  }
}
</script>

Explore demo 2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to make multiple calls following a successful AJAX request?

Here is an AJAX call I am setting up. The first step is to hit the endpoint dofirstthing.do. Once that is successful, the next step is to make another call with "param1" as the query parameter. Now, my question is - how can I make a third call with "param ...

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

Javascript Select Element with No Options

I'm currently working on a <select> element that is being populated from an array using the following code snippet: <select id="selector" name="selector"</select> <button type=button onclick=populateSelect(states)>Click me1!</ ...

Extract the label from Chip component within the onClick() event in material-ui

-- Using Material-UI with React and Redux -- Within my material-ui table, there are <TableRow> elements each containing multiple <TableCell> components with <Chip> elements. These <Chip> components display text via their label prop ...

Refresh the DIV element that houses dynamically generated <ul> HTML content after submitting new inputs

UPDATE: After delving into the code of nested include files in the child PHP file, I've identified conflicts with the parent PHP include files. This means that the child PHP file/div relies on the parent being refreshed, preventing me from refreshing ...

React Native: Implementing scroll-based header animations in ScrollView

Currently, I am working on implementing an animated header with ScrollView on the screen. In this implementation, I need to set my view based on the Y position of the ScrollView during scrolling. This is how it's done: const onScroll = ({ nativeEvent: ...

Is it possible to modify the CSS styling of the file_field?

I am looking to customize the appearance of the file_field in CSS. Rather than displaying the default browse button, I would like to use a simpler upload button for file submission. What steps can I take to modify the CSS of the file_field and replace it ...

Are there any potential performance implications to passing an anonymous function as a prop?

Is it true that both anonymous functions and normal functions are recreated on every render? Since components are functions, is it necessary to recreate all functions every time they are called? And does using a normal function offer any performance improv ...

Building a time series collection in MongoDB with Node.js

Are there any npm packages available for creating mongodb time series collections using node.js? I did not find any documentation related to this in the mongoose npm package. ...

What is the best way to arrange a GeoJSON features array based on a specific property value?

I need help sorting a GeoJSON file based on a property and then slicing it to keep only the top 5 features. For instance, I want to take this GeoJSON and arrange it in descending order by the incidents property: ... [ -75.1972382872565 ...

In Javascript, an error occurs when something is undefined

I've been grappling with a Javascript issue and seem to have hit a roadblock. In Firefox's console, I keep encountering an error message that says "info[last] is undefined," and it's leaving me puzzled. The problematic line appears to be nu ...

Discover Xml information or Json object displayed as XML tree in Html using Javascript

Looking for a way to display my JSON object or XML data in HTML similar to how React does it. I found this component on GitHub: https://github.com/marushkevych/xml-display-component, but I prefer not to mix JavaScript and React.js. Can anyone offer some gu ...

How to retrieve the Vue instance within a Laravel Inertia component

I am facing a challenge in extracting data from a dynamic HTML containing interpolation within a Vue component using Inertia. Here is a snippet of my code: <template> <div v-if="parsed" v-html="parsed"></div> </t ...

Disable sessionStorage property when closing tabs on all pages

I am brand new to the world of .NET development, currently immersing myself in an ASP application with web forms. One particular page in the application contains a table. When a user clicks on a row within this table, it triggers the opening of a new tab. ...

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value & ...

Issue with $cookies not functioning properly in Angular 1.4.2 version

Having trouble with Angular and injecting $cookies into a controller. The $cookies work fine in a service, but encountering issues in this specific controller. var app = angular.module('app', [ "ui.router", "ngCookies", 'ui.boo ...

Vue's unshift method only appends new items to the beginning of an

Could you help me with a problem similar to this one: The array I am working with looks like this: remate: {id:1, lotes: [{id:1, nombre: lalala}, {id:2, nombre: lololo}]} My issue arises when attempting to add new items to remate.lotes. While the push m ...

Unable to load the manually added module in the /node_modules/ folder

I'm trying to manually use a module that I placed in the /node_modules/ directory. After copying and pasting the files and installing dependencies with npm, I encountered an issue while using NWJS 0.16.0. When attempting var speech = require('sp ...

Content in static JSON file failing to display in NextJS

I recently started using Next, and I've encountered an issue. There is a static JSON file located in the root of my project directory, structured as follows: {"data":[{"id":1,"attributes":{"name":"Test Prod ...

What is the best way to incorporate a CSS transition without any dynamic property changes?

Is there a way to add a transition effect to a header when its size changes without a specified height value in the CSS? The header consists of only text with top and bottom padding, so as the text changes, the height adjusts accordingly. How can I impleme ...