Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the HTML5 Video Object with jQuery

Im having problems getting at the HTML5 video tag with jQuery. Here is my code:

HTML code:

<video id="vid" height="400" width="550">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogv" type="video/ogg">
</video>

Javascript code:

function playVid(){
    console.log($('#vid'));
    console.log($('#vid')[0]);
    $('#vid')[0].currentTime=5;
    $('#vid')[0].play()
}

$(document).ready(){
    playVid();
}

The code breaks on the .currentTime line with the following error:

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Here is the bit that I cant figure out - the first console.log shows the object I would expect, inside this object is another object called 0 and this holds all the HTML5 video properties and methods you would expect, including .currentTime.

However as soon as I do the second log of $('#vid')[0] it shows the HTML code for the video tag, and not the object I was after called 0. I get the exact same results for console.log($('#vid')["0"]) and console.log($('#vid').get(0)).

Is there a way of getting at the object called 0 in the object returned by $('#vid') that works in jQuery?

like image 813
Jimmery Avatar asked Jun 27 '12 16:06

Jimmery


People also ask

What is $() in jQuery?

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.

How do I select something in jQuery?

The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field. Syntax: $(selector). select(function);

What is the correct HTML5 element for playing video?

The <video> HTML element embeds a media player which supports video playback into the document.

What is HTML5 video tag?

The HTML5 “video” element specifies a standard way to embed a video on a web page. There are three different formats that are commonly supported by web browsers – mp4, Ogg, and WebM.


1 Answers

I think you are trying to interact with the video element before it is ready.

Try something like this:

function loadStart(event)
{
    video.currentTime = 1.0;
}

function init()
{
    video.addEventListener('loadedmetadata', loadStart, false);
}
document.addEventListener("DOMContentLoaded", init, false);

Source: HTML5 Video - Chrome - Error settings currentTime

like image 69
Crake Avatar answered Nov 04 '22 01:11

Crake