Omar Juvera
Omar Juvera

Reputation: 12297

Create a new html5 video object with jQuery

How can you create a video element with jQuery, and add it's properties like control to true (<video control>), add and remove video sources (<source src='http://somesite.com/somevideo.mp4'), etc?

I would like to set all it's options before loading (like autoplay, true or false, etc)

I tried this without success (It worked with images, but not video):

$( document ).ready(function() {
var photo = $('<img />', {
              id: 'photo',
              src: 'http://lorempixel.com/400/200/city/',
              alt: ''
              });
photo.appendTo($('#gallery'));

var video = document.createElement('video');
    alert( video.toSource() ); //For testing
    video.id = 'video';
    video.source.src = 'http://video-js.zencoder.com/oceans-clip.mp4';
    video.type = 'video/mp4';
    video.control = true;
video.appendTo($('#gallery'));
});

jsFiddle: https://jsfiddle.net/9cnaz3ju/1/

Upvotes: 6

Views: 18534

Answers (1)

j08691
j08691

Reputation: 207923

Like this:

var video = $('<video />', {
    id: 'video',
    src: 'http://video-js.zencoder.com/oceans-clip.mp4',
    type: 'video/mp4',
    controls: true
});
video.appendTo($('#gallery'));

jsFiddle example

    var photo = $('<img />', {
        id: 'photo',
        src: 'http://lorempixel.com/400/200/city/',
        alt: ''
    });
    photo.appendTo($('#gallery'));

    var video = $('<video />', {
        id: 'video',
        src: 'http://video-js.zencoder.com/oceans-clip.mp4',
        type: 'video/mp4',
        controls: true
    });
    video.appendTo($('#gallery'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="gallery"></div>

Just follow the same basic format as your see with the image element.

Upvotes: 14

Related Questions