Matt D. Webb
Matt D. Webb

Reputation: 3314

jquery plugin, reference video element in DOM

I have started jQuery plugin where I want to retrieve the .duration and .currentTime on a HTML5 video, from within a bound .on('click', ) event.

I am struggling to capture this information within my plugin.registerClick function, here is my code:

(function ($) {

$.myPlugin = function (element, options) {

    var defaults = {
            videoOnPage: 0,
            dataSource: 'data/jsonIntervals.txt',
            registerClick: function () { }
    }

    var plugin = this;

    plugin.settings = {}

    var $element = $(element);
         element = element;

    plugin.init = function () {

        plugin.settings = $.extend({}, defaults, options);

        $element.on('click', plugin.registerClick);

        getJsonIntervals();
    }

    plugin.registerClick = function () {

        var duration = $('video').get(plugin.settings.videoOnPage).duration;

        console.log('duration: ' + duration);
    }

    var startTimes = [];
    var dataSet = false;

    var getJsonIntervals = function () {

        if (dataSet == false) {
                //calls a $.getJSON method.
                //populates startTimes
                //updates dataSet = true;
        };
    }

    plugin.init();

}

$.fn.myPlugin = function (options) {
    return this.each(function () {
        if (undefined == $(this).data('myPlugin')) {
            var plugin = new $.myPlugin(this, options);
            $(this).data('myPlugin', plugin);
        }
    })
};

})(jQuery);

$(function () {
    $('#button1').myPlugin();
});

Here my sample jsFiddle Click Here

Upvotes: 0

Views: 52

Answers (1)

Benny Lin
Benny Lin

Reputation: 536

Seems to work for me:

plugin.registerClick = function () {
  var video = $('video').get(0);            
  console.log('duration: ' + video.duration);
  console.log('currenttime: ' + video.currentTime);
}

http://jsfiddle.net/p4w040uz/2/

You need to play the video first then click the button. The browser has to retrieve the meta data first before it can return it.

Additional reference material you can read up:

http://www.w3schools.com/tags/av_event_loadedmetadata.asp

http://www.w3.org/2010/05/video/mediaevents.html

Upvotes: 1

Related Questions