javascript - Using clickToggle and closing element when another is clicked -


i wrote code based off of felix kling's response click toggle. wondering if there better way of writing it, , how close element when clicked.

i using play points of video on click , close them on secondary click.

i have wrote function close on escape classes, slows down , breaks event completing.

$(document).on('keydown', function(e) {     if(e.keycode == 27) {         var buttons = $("button");         if ( buttons.hasclass("open") ) {             myvideo.currenttime = 2.8;             myvideo.play();             settimeout(function() {                 myvideo.pause();             }, 540);             buttons.removeclass("open");         }     } })   var myvideo = document.getelementbyid("video");  $("#button-1").clicktoggle(function() {     myvideo.currenttime = 2;     myvideo.play();     $(this).addclass("open");     settimeout(function() {         myvideo.pause();     }, 900); }, function() {     myvideo.currenttime = 2.8;     myvideo.play();     settimeout(function() {         myvideo.pause();     }, 540); });  $("#button-2").clicktoggle(function() {     myvideo.currenttime = 3.05;     myvideo.play();     settimeout(function() {         myvideo.pause();     }, 850); }, function() {     myvideo.currenttime = 3.8;     myvideo.play();     settimeout(function() {         myvideo.pause();     }, 680); }); 

well, more reliable way pause video @ correct spot, listen timeupdate event:

myvideo.addeventlistener("timeupdate", function(){     if(myvideo.currenttime >= 2.9) {         myvideo.pause();     } }); 

of course, wouldn't want listener keep executing when start play next segment. remove listener, , replace new 1 next segment. or store video start , stop times in array this:

var videosegments = [         { starttime: 2, endtime: 2.9},         { starttime: 2.8, endtime: 3.34},         { starttime: 3.05, endtime: 3.9},         { starttime: 3.8, endtime: 4.48}     ]; 

now can use 1 listener:

myvideo.addeventlistener("timeupdate",function(){     if(myvideo.currenttime >= videosegments[currentsegment].endtime) myvideo.pause(); }); 

and don't need clicktoggle either if onclick function this:

$(button).click( function() {       ...other stuff here...       currentsegment++;      myvideo.currenttime = videosegments[currentsegment].starttime;      myvideo.play(); }); 

each time click, advances video next segment , plays it. listener stop video when reaches right spot.

here's working example: http://jsfiddle.net/w30j2acc/2/


Popular posts from this blog