jQuery stop video script - javascript

This script work perfectly, but what it does is stops an instance of a playing video if a new video is started. How would I rewrite this to stop ALL instances of playing videos when the function stopAllButMe(); is called?
function stopAllButMe(playerState, player) {
if (playerState=='PLAYING') {
var myId = player.getId();
projekktor('*').each(function() {
if (this.getId()!==myId) {
this.setStop();
}
});
}
}
projekktor('*').each(function() {
this.addListener('state', stopAllButMe);
});

function stopAllButMe(playerState) {
if (playerState=='PLAYING') {
projekktor('*').each(function() {
this.setStop();
});
}
}
projekktor('*').each(function() {
this.addListener('state', stopAllButMe);
});
The 'if' statement was checking against the input.

function stopAllButMe (state, player) {
//iterate through each of the `<video>` elements
$.each($('video'), function () {
//check if the current iteration is the same element that got passed into this function
if (this.id != player.id) {
//stop any `<video>` element that isn't the one passed into this function
this.stop();
}
});
}
//find each `<video>` element and add an event handler for the `state` event
$('video').bind('state', stopAllButMe);
This assumes that each <video> tag has it's own unique ID.

Related

call function (audio playing) in order

I hava a function that playing audios in order. But there may be a case where the function is called almost at the same time, and all audios playing is mixed. How can I call the same function where audios order of the second call is played after the audios order of the first call.
function playSound() {
$('#content').append('<audio id="ding" src="ding.wav" preload="auto"></audio>');
$('#ding')[0].play();
$('#ding')[0].onended = function() {
$('#content').append('<audio id="number" src="sound/voice/number.wav" preload="auto"></audio>');
$('#number')[0].play();
$('#number')[0].onended = function() {
$('#content').append('<audio id="goToCounter" src="sound/voice/goToCounter.wav" preload="auto"></audio>');
$('#goToCounter')[0].play();
}
}
}
One possible way is to have a counter that counts the number of times the playSound function is called. If it is still in the middle of playing sounds, increase the counter, but return from the function. Only after the playing of the three sounds is finished, you call playSound again if there are still calls in the queue.
var numberOfTimesAudioHasStarted = 0;
function playSound(buttonClicked) {
if(buttonClicked === true){
numberOfTimesAudioHasStarted++;
}
if(numberOfTimesAudioHasStarted > 1 && buttonClicked === true){
return;
}
$('#content').append(
'<audio id="ding" src="https://thumbs.dreamstime.com/audiothumb_22779/227796222.mp3" preload="auto"></audio>');
$('#ding')[0].play();
$('#ding')[0].onended = function() {
$('#content')
.append(
'<audio id="number" src="https://thumbs.dreamstime.com/audiothumb_22779/227796222.mp3" preload="auto"></audio>');
$('#number')[0].play();
$('#number')[0].onended = function() {
$('#content')
.append(
'<audio id="goToCounter" src="https://thumbs.dreamstime.com/audiothumb_11413/114136296.mp3" preload="auto"></audio>');
$('#goToCounter')[0].play();
$('#goToCounter')[0].onended = function() {
numberOfTimesAudioHasStarted--;
if(numberOfTimesAudioHasStarted > 0){
playSound(false);
}
}
}
}
}
$('button').click(function() {
playSound(true);
});
<div id="content"></div>
<button>play</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note that this function keeps adding audio elements to the page every time the function runs. This is bad practice, since no two elements with the same id should be present on a page.

Remove EventListener by returning false

My _() function takes a HTML element ID and returns document.getElementById(str). Below I have many eventListeners that either listen for a button click or keyboard event. However since this JS file is shared among many pages, some HTML Elements do not exist for certain pages, thus the addEventListener() function spits out an error and terminates the execution everytime it tries to bind a event listener to a non-existent HTML Element. How can I prevent this from happening and let the code execution continue? In other words, how can I catch these errors?
function _(str) {
var k = document.getElementById(str);
if(k){
return document.getElementById(str);
} else {
return false;
}
}
document.addEventListener("DOMContentLoaded", function () {
//Button Event Listeners
_("commentlink").addEventListener("click", showCommentBox);
_("help_retract").addEventListener("click", function () {
$(".help_box").toggle(500);
_("commentlink").style.display = "block";
$("#commentbox").hide();
})
_("help_link").addEventListener("click", function () {
$("#help_box").toggle(500);
});
_("q-help-link").addEventListener("click", function (){
$("#q-help").toggle(500);
});
_("comment-textbox").addEventListener("keyup", checkCharLength);
_("submit-comment").addEventListener("click", submitComment);
_("voteUp").addEventListener("click", function () {
submitVote(1);
})
_("voteDown").addEventListener("click", function () {
submitVote(-1);
})
//Automatic Events:
if (checkCookie("comm_sub")) {
showCommentBox();
}
});
Try adding this function:
window.onerror = function(){
return true;
}
If that doesn't work, surround each .addEventListener with:
try {
// .addEventListener here
} catch (e) { // Ignore Errors }

html5 audio bind timeupdate before element exists

im trying to bind the "timeupdate" event from an audio tag, which doesn't exist yet. I was used to do it this way:
$("body").on("click","#selector", function(e) {
});
I tried this with the audio tag:
$("body").on("timeupdate", ".audioPlayerJS audio", function(e) {
alert("test");
console.log($(".audioPlayerJS audio").prop("currentTime"));
$(".audioPlayerJS span.current-time").html($(".audioPlayerJS audio").prop("currentTime"));
});
This doesn't work though. Is this supposed to work? Or what am I doing wrong?
Any help is highly appreciated.
There is a fiddel for you: jsfiddel
Apparently media events( those specifically belonging to audio or video like play, pause, timeupdate, etc) do not get bubbled. you can find the explanation for that in the answer to this question.
So using their solution, I captured the timeupdate event,
$.createEventCapturing(['timeupdate']);
$('body').on('timeupdate', '.audioPlayerJS audio', updateTime); // now this would work.
JSFiddle demo
the code for event capturing( taken from the other SO answer):
$.createEventCapturing = (function () {
var special = $.event.special;
return function (names) {
if (!document.addEventListener) {
return;
}
if (typeof names == 'string') {
names = [names];
}
$.each(names, function (i, name) {
var handler = function (e) {
e = $.event.fix(e);
return $.event.dispatch.call(this, e);
};
special[name] = special[name] || {};
if (special[name].setup || special[name].teardown) {
return;
}
$.extend(special[name], {
setup: function () {
this.addEventListener(name, handler, true);
},
teardown: function () {
this.removeEventListener(name, handler, true);
}
});
});
};
})();

Need help stopping slideshow using jQuery

I've run into an issue with jQuery code that I'd like some help on. While the next and previous buttons work correctly, there appears to be an issue correctly stopping a slideshow. This is probably something we're completely overlooking, but I can't see what.
There is no JavaScript errors showing in the console. The interrupt method was being reached - at one point I had console.log calls in there to verify (cleaned up for presentation reasons).
http://jsfiddle.net/eLn83ep0/
Your help is much appreciated.
The below code is the functionality for prev/stop/start/next:
if ($(settings.next).size()) {
$(settings.next).bind('click.scrollface', function (e) {
methods.interrupt.call($this);
methods.next.call($this);
});
}
if ($(settings.pause).size()) {
$(settings.pause).bind('click.scrollface', function (e) {
methods.interrupt.call($this);
});
}
if ($(settings.play).size()) {
$(settings.play).bind('click.scrollface', function (e) {
methods.interrupt.call($this);
methods.start.call($this);
});
}
/*
* Setup up prev bindings
*/
if ($(settings.prev).size()) {
$(settings.prev).bind('click.scrollface', function (e) {
methods.interrupt.call($this);
methods.prev.call($this);
});
}
Here is the method for interrupt:
interrupt: function (time) {
return $(this).each(function () {
var data = $(this).data('scrollface');
console.log(data);
console.log('...');
if (!data) {
return false;
}
var $this = $(this),
period = 0;
/*
* Stop the timer, and wait a period of time before restarting it.
* Period defaults to the timer interval
*/
if (data.timer) {
if (typeof time !== "number") {
period = data.interval;
} else {
period = time;
}
methods.stop.call(this);
setTimeout(function resume_timer () {
clearInterval(data.timer);
data.timer = null;
methods.start.call($this);
}, period);
}
});
},
if ($(settings.pause).size()) {
$(settings.pause).bind('click.scrollface', function (e)
methods.stop.call($this);
});
}
if ($(settings.play).size()) {
$(settings.play).bind('click.scrollface', function (e) {
methods.start.call($this);
});
}
and delete the interrupt call in prev and next
//methods.interrupt.call(this);
because the interrupt method stopping the interval method and after timeout starting again, so most time you pause in this timeout but after this timeout the interrupt method starting the intervall again and dont care if you stoped it manually
see your updated fiddle working here http://jsfiddle.net/7ko4rdda/
Edit:
if you call interrupt with 0 for the buttons prev next click handler then you have the expected behavier that the period for the intervall starts new after next/prev click
if ($(settings.prev).size()) {
$(settings.prev).bind('click.scrollface', function (e) {
methods.interrupt.call($this,0);
methods.prev.call($this);
});
}
if ($(settings.next).size()) {
$(settings.next).bind('click.scrollface', function (e) {
methods.interrupt.call($this,0);
methods.next.call($this);
});
}
http://jsfiddle.net/7ko4rdda/1/

Wait until div is not visible to process next line

I need to write some code which is supposed to wait until a predefined div is no longer visible in order to process the next line. I plan on using jQuery( ":visible" ) for this, and was thinking I could have some type of while loop. Does anyone have a good suggestion on how to accomplish this task?
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if ($(".mstrWaitBox").attr("visibility")!== 'undefined') || $(".mstrWaitBox").attr("visibility") !== false) {
alert('inside else');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if (!$(".mstrWaitBox").is(":visible")) {
alert('inside if');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
div when not visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt">​
</div>​
div when visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt" visibility="visible">​
</div>​
You can use the setTimeout function to poll the display status of the div. This implementation checks to see if the div is invisible every 1/2 second, once the div is no longer visible, execute some code. In my example we show another div, but you could easily call a function or do whatever.
http://jsfiddle.net/vHmq6/1/
Script
$(function() {
setTimeout(function() {
$("#hideThis").hide();
}, 3000);
pollVisibility();
function pollVisibility() {
if (!$("#hideThis").is(":visible")) {
// call a function here, or do whatever now that the div is not visible
$("#thenShowThis").show();
} else {
setTimeout(pollVisibility, 500);
}
}
}
Html
<div id='hideThis' style="display:block">
The other thing happens when this is no longer visible in about 3s</div>
<div id='thenShowThis' style="display:none">Hi There</div>
If your code is running in a modern browser you could always use the MutationObserver object and fallback on polling with setInterval or setTimeout when it's not supported.
There seems to be a polyfill as well, however I have never tried it and it's the first time I have a look at the project.
FIDDLE
var div = document.getElementById('test'),
divDisplay = div.style.display,
observer = new MutationObserver(function () {
var currentDisplay = div.style.display;
if (divDisplay !== currentDisplay) {
console.log('new display is ' + (divDisplay = currentDisplay));
}
});
//observe changes
observer.observe(div, { attributes: true });
div.style.display = 'none';
setTimeout(function () {
div.style.display = 'block';
}, 500);
However an even better alternative in my opinion would be to add an interceptor to third-party function that's hiding the div, if possible.
E.g
var hideImportantElement = function () {
//hide logic
};
//intercept
hideImportantElement = (function (fn) {
return function () {
fn.apply(this, arguments);
console.log('element was hidden');
};
})(hideImportantElement);
I used this approach to wait for an element to disappear so I can execute the other functions after that.
Let's say doTheRestOfTheStuff(parameters) function should only be called after the element with ID the_Element_ID disappears, we can use,
var existCondition = setInterval(function() {
if ($('#the_Element_ID').length <= 0) {
console.log("Exists!");
clearInterval(existCondition);
doTheRestOfTheStuff(parameters);
}
}, 100); // check every 100ms

Categories

Resources