videoタグのplayにイベントを割り当てる
HTML5のvideoタグで再生開始されたときに特定の処理を行いたかったので、playイベントにplayというメソッドを割り当ててみたときのメモ
iPhoneとかでは普通にvideoタグの部分を押したらplayイベント発生するけど、Androidの一部端末では onclick="this.play();"とかみたいにclick時にplayを実行してやら無いといけない端末もあるため、clickイベントからplay呼び出すようにしてある
<script type="text/javascript"> <!-- // playメソッドにイベントを割り当てる jQuery.fn.play = function( fn ) { return (fn) ? this.bind( "play", fn ) : this.trigger( "play"); }; $(function(){ $('video').play(function(){ // video.play();時に実行される処理 }); // playイベント発生しない端末用にclickイベント発生時にthis.play()してあげる $('video').click(function(){ this.play(); }); }); --> </script> <video src="example.mp4"> </video>
参考にしたのはjQueryドキュメントについてたコメント欄
.trigger() | jQuery API Documentation
I have the exact same problem. I'm trying to write a jQuery plugin for HTML 5 Video ( with fallbacks) but the problem is the Video Element (the HTML Node) has a method ( a property ?) called "play". So when I add a "play" method to the jQuery.fn object and then try to trigger a "play" event on a video element, the event is fired twice ! For example, I create a new method called "play" : jQuery.fn.play = function( fn ) { return (fn) ? this.bind( "play", fn ) : this.trigger( "play"); }; and then I try to use it : $("video").play(function() { alert('failed') }); The browser shows two alert windows. Can anyone help ?
まぁ、このコメントではplayイベントにplayメソッド割り当てたら、なんかよくわかんないけど2回実行されちゃうよ、助けてーってことらしいけどw