0

Given this markup

<p><a href="#">LOAD VIDEO</a></p>

<video id="video" controls width="560">
    <source id="webm" type="video/webm" />
    <span>zoom-club.webm</span>
</video>

And this script

$(document).ready(function(){

    $('a').on('click',function(){

        var path = "../assets/" + $('span').text();

        $('source').attr('src', path);

        $('video#video').load();
        $('video#video').play();

    });

});

Why do I get this error?

Uncaught TypeError: undefined is not a function

This will actually work using tradition Javascript and getElementById, but for some reason the way I am referencing the video tag is broken. What gives?

mmcglynn
  • 7,668
  • 16
  • 52
  • 76
  • possible duplicate of [Play/pause HTML 5 video using JQuery](http://stackoverflow.com/questions/4646998/play-pause-html-5-video-using-jquery) – Qantas 94 Heavy Aug 23 '14 at 13:07

1 Answers1

3

You get this error because

$('video#video')

gives you a jQuery object back. But it doesn't have a play() method.

So you need to extract the DOM object from it:

$('video#video')[0]

Now on this you can invoke play():

$('video#video')[0].play();
pid
  • 11,472
  • 6
  • 34
  • 63
  • 1
    i think `.get(0)` is better because it does not produce error if object contains no elements – andrew Aug 23 '14 at 13:08
  • Good point! But his HTML is static, how could it not contain the element? In the general case it's even NECESSARY to use get()! Thanks :) – pid Aug 23 '14 at 13:10
  • There is no difference between [0] and get(0), both will return undefined, if the collection is empty. In fact, if you look into jQuery code, jQuery will do the exact same thing, if you pass a positive number. Beside this, jQuery has a .load and due to the fact, how this method works, it actually does invoke the native load method, altough you shouldn't use it because jQuery will also additionally dispatch a load event. – alexander farkas Aug 23 '14 at 13:41