Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-play an HTML5 video on Dom Load using jQuery

I'm trying to play a video as soon as the dom has loaded using jQuery. This is my code:

HTML

<video id="video" width="420">
  <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  <source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
  <p>Your browser does not support HTML5 video.</p>
</video>

JS (script.js)

$(document).ready(function() {
  $(#video).play();
});

When you dom loads the video does not play, where am I going wrong? Thanks in advance.

like image 648
Jamie Fearon Avatar asked Apr 05 '13 19:04

Jamie Fearon


People also ask

How to autoplay video in HTML using jQuery?

You can use: $("#video_player")[0]. play();

How to play video on page load using jQuery?

In jQuery, the video file is first selected using a selector and the actual element is selected using the get() method. Then the play() method is used on this element to attempt to start the video. The pause() method in JavaScript is used to pause the playback of a media file.

How do I get a video to automatically play in HTML?

The HTML autoplay Attribute is used to specify that the audio/video should automatically start playing when web page is loaded. It is a Boolean attribute. Uses It can be used with <audio> and <video> element. Example 1: Here the autoplay attribute is used with the <video> tag.

How do you play video as soon as the Web page loads?

The autoplay property sets or returns whether a video should start playing as soon as it is loaded. This property reflects the <video> autoplay attribute. When present, it specifies that the video should automatically start playing as soon as it is loaded.


2 Answers

The jQuery selector $("#video") returns a jQuery object. Since play() is a function of the DOM element, you must get the DOM element with:

$("#video").get(0);

before using .play() method:

$("#video").get(0).play();

Edit: You can also use HTML5 selected tags in case jQuery fall back. Note the autoplay tag.

<video controls="controls" autoplay="autoplay" loop="loop"
width="233" height="147" poster="//www.cdn.com//video.png"
preload="auto" title="Video">
    <source src="//www.cdn.com/video.mp4" type="video/mp4"/>
    <source src="//www.cdn.com/video.ogv" type="video/ogv"/>
    <source src="//www.cdn.com/video.webm" type="video/webm"/>
</video>
like image 174
Justin McDonald Avatar answered Sep 21 '22 17:09

Justin McDonald


I know is not jQuery but in standard javascript with html5 you can use:

var video = document.getElementById("target_video");
video.autoplay = true;
video.load(); 
like image 23
insecureabnormality Avatar answered Sep 18 '22 17:09

insecureabnormality