Johnny
Johnny

Reputation: 9964

Can't select specific HTML5 video with jQuery within a plugin

I have a plugin for html5 videos that I'm currently working on and want to select specifically each video separately on a web page. It starts as you would usually start:

(function($) {

$.fn.videoPlayer = function(options) {


    var settings = {  
        playerWidth : '0.95', // Default is 95%
        videoClass : 'video'  // Video Class
    }

    // Extend the options so they work with the plugin
    if(options) {
        $.extend(settings, options);
    }



    // For each so that we keep chainability.
    return this.each(function() {       


        // Basic Variables 
        $this = $(this);
        $settings = settings;

So since I'm doing for each in the plugin I expected that each video would be selected separately and specifically but this is not the case. So if I want to do something like this:

$this.play();

It does not work. Instead, I have to do this or I get an error about that element not having that method:

$this[0].play();

This won't work for a plugin since I need to apply this to all videos and this will only select the first video on the page. So how do I go about fixing this? I'm also having some trouble with waiting for loadedmetadata which seems to mess up all the videos on the page in some way (I assume because I have to wait or because of a related error to what I've mentioned above?)

Any ideas?

Upvotes: 0

Views: 200

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219936

.play() is a native DOM method, so use this directly:

this.play();

Since you're first wrapping this in jQuery - and only calling play on $this - you get an error, as jQuery does not have a play method.


P.S. Using $this[0].play() would also work. It won't select the first video, since it's using the this value of the each callback, which only ever has one element in its collection...

Upvotes: 1

Related Questions