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

Incorporate text into the URL of the image

Got a URL of an image like this: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg', and looking to add 240x240 within the URL. Current Url: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg Desire ...

I'm interested in learning about the most efficient practices for handling JSON, performing math operations, and utilizing loops in JS/React. What techniques

Short version: I'm working with a large array of JSON objects (60K+ elements) in my application I need to perform various mathematical operations such as comparison and addition Currently, I am handling this through multiple for loops (simplified ...

"How to eliminate the hash symbol from a URL using react-router-dom in a React.js

Recently started learning react.js and running into an issue with the URL structure while using react-router-dom v6 in my project. Specifically, I'm finding a problem with the # symbol in the URL. For instance: {url}/#/dashboard I would like it to b ...

Ways to retrieve the response object from an express application

I am currently working on developing a nodejs application with mysql and my objective is to have my controllers and messages separated into different files. Below are examples of what I am aiming for: First, here is a snippet from my auth controller file: ...

When using React-hook-form, you need to tap twice to delete the last character in the input field, and double tap to enter the first

I have been using React Hook Form to validate my form with multiple inputs. Everything works perfectly, except I noticed one issue where I have to press the backspace key twice to delete the last character and also twice to enter the first character. For e ...

Error: Attempting to access 'push' property on an undefined object

Encountered an Error After implementing the useNavigate function, I successfully resolved the issue. let params = useParams(); let navigate = useNavigate(); const dispatch = useDispatch(); const productId = params.id; const [qty, setQty] = useStat ...

Having trouble rendering to the framebuffer due to issues with the texture

In the process of incorporating shadow maps for shadows, I am attempting to render a scene to a separate framebuffer (texture). Despite my efforts, I have not been able to achieve the desired outcome. After simplifying my codebase, I am left with a set of ...

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...

Establish map boundaries using the longitude and latitude of multiple markers

Utilizing Vue, I have integrated the vue-mapbox component from this location: I've made sure to update the js and css to the latest versions and added them to the index.html: <!-- Mapbox GL CSS --> <link href="https://api.tiles.mapbox.com/m ...

Node API is failing to insert user data into MongoDB

I'm currently developing a Restful API using Node.js and storing data in Mongodb, focusing on the user registration API. app.js apiRoutes.post('/signup', function(req, res) { if (!req.body.name || !req.body.password) { res.json({suc ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

problem with the video pathway in the javascript document

I'm currently in the process of putting together a Video gallery playlist using HTML, CSS, and JavaScript. So far, I've set up the html and css files along with two js files. The first js file contains all the video information as shown here: ...

Eliminating bottom section in HTML/CSS

I've got this code snippet: new WOW().init(); /* AUTHOR LINK */ $('.about-me-img img, .authorWindowWrapper').hover(function() { $('.authorWindowWrapper').stop().fadeIn('fast').find('p').addClass('tr ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

Tips for invoking a function using ng-model together with the ng-model value

Within a div element, I have a text field where I am using ng-model to capture the value. I need to trigger a function for validation when a date is entered in the text field. How can I achieve this while still utilizing ng-model? Any suggestions on how to ...

Proper method for positioning text in a line

Trying to recreate the image below, but facing alignment issues with the text in my code. How can I vertically align the text so that they are aligned like in the photo? Flexbox hasn't helped due to varying text lengths causing misalignment. const ...

Overwriting Resolved Data in Angular UI-Router Child States

I'm facing an issue where the resolve function is the same in both parent and child states, but I need it to return different values based on the child state. Instead of customizing the implementation for each state, it seems to be inheriting the beha ...

Creating a dropdown list for months in Vue.js

I have managed to get this working in my test project, but I'm struggling to understand the inner workings of it. The Vue.js implementation seems a bit complex to me, and I believe there might be a simpler way to achieve the same result. Any advice on ...

How can I modify a prop within a nested component?

I'm currently working with Vue.js version 2.5 and facing a challenge with a list. Each item in the list has a button that toggles its details. The requirement is such that when one button is clicked, all other details should be closed and only the sel ...

Creating a dropdown navigation menu using jQuery

I have been experimenting with creating a customized Drop Down menu using ul li and Jquery, following this helpful Tutorial. Here is the sample HTML Code for testing: <div id="dd" class="wrapper-dropdown-3" tabindex="1"> <span>OS</span> ...