Bind event listener from outside function - javascript

How can I from the outside of my init function, fire off the reset function within init.
I want my reset function to reset all variables set from the collection of the images (3 in this case) which is bound 3 times. My example here isn't working I'm aware.
Here's my code:
document.getElementsByClassName('zoomer-start')[0].addEventListener('click', init);
document.getElementsByClassName('zoomer-reset')[0].addEventListener('click', reset);
function init() {
var images = document.querySelectorAll('.zoomer-img');
for (var i = 0; i < images.length; i++) {
(function() {
var image = images[i];
var zoomer = new Hammer(image);
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
var clicked = false;
var adjustScale = 1;
var adjustDeltaX = 0;
var adjustDeltaY = 0;
var currentScale = null;
var currentDeltaX = null;
var currentDeltaY = null;
zoomer.on('tap', function (e) {
if (!clicked) {
zoomer.get('pinch').set({enable: true});
zoomer.get('pan').set({enable: true, direction: Hammer.DIRECTION_ALL});
clicked = true;
} else {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
}
if (currentScale > 1) {
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
} else {
adjustScale = 2;
}
currentScale = adjustScale * e.scale;
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('pan pinch', function (e) {
currentScale = Math.max(1, Math.min(adjustScale * e.scale, 4));
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
var scaledX = ((((image.width * currentScale) / 2) - (image.width / 2)) / currentScale);
if (currentDeltaX > scaledX)
currentDeltaX = scaledX;
if (currentDeltaX < -scaledX)
currentDeltaX = -scaledX;
var scaledY = ((((image.height * currentScale) / 2) - (image.height / 2)) / currentScale);
if (currentDeltaY > scaledY)
currentDeltaY = scaledY;
if (currentDeltaY < -scaledY)
currentDeltaY = -scaledY;
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('panend pinchend', function () {
adjustScale = currentScale;
adjustDeltaX = currentDeltaX;
adjustDeltaY = currentDeltaY;
});
function reset() {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
currentScale = null;
currentDeltaX = null;
currentDeltaY = null;
image.style.transform = 'scale(' + 1 + ') translate3d(' + 0 + 'px, ' + 0 + 'px, 0)';
}
})();
}
}

To call function(s) from withinn scope you have to pass it somehow to the surronding scope. One possible example for Your code:
var resets = [];
function init() {
[...]
for (var i = 0; i < images.length; i++) {
(function() {
[...]
resets[i]=function reset() {
[...]
})
And then call them naively:
resets[0](); resets[1](); resets[2];
Or via:
resets.forEach(function(f) { f(); } );

Having your functions inside the init function gives them Private SCOPE only (can only be accessed from within the init function) To give them global scope you will have to move them outside of the init function which will require some code restructuring.

With the code as written, you can't. The reset function is entirely private to the code in the anonymous function inside init. Even other code in init can't access it, much less code outside init.
I say "it" above, but really, you have multiple reset functions, one for each image.
You could, of course, move your code trying to use it as a click handler into that anonymous function inside init. That's basically your only real option, other than creating an array or similar of reset functions that you expose outside init.

Thanks guys, I learned something today! Here's my working example. Really really neat:
var resets = [];
document.getElementsByClassName('zoomer-start')[0].addEventListener('click', init);
document.getElementsByClassName('zoomer-reset')[0].addEventListener('click', function () {
var images = document.querySelectorAll('.zoomer-img');
for (var i = 0; i < images.length; i++) {
resets[i]();
}
});
function init() {
var images = document.querySelectorAll('.zoomer-img');
for (var i = 0; i < images.length; i++) {
(function(i) {
var image = images[i];
var zoomer = new Hammer(image);
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
var clicked = false;
var adjustScale = 1;
var adjustDeltaX = 0;
var adjustDeltaY = 0;
var currentScale = null;
var currentDeltaX = null;
var currentDeltaY = null;
zoomer.on('tap', function (e) {
if (!clicked) {
zoomer.get('pinch').set({enable: true});
zoomer.get('pan').set({enable: true, direction: Hammer.DIRECTION_ALL});
clicked = true;
} else {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
}
if (currentScale > 1) {
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
} else {
adjustScale = 2;
}
currentScale = adjustScale * e.scale;
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('pan pinch', function (e) {
currentScale = Math.max(1, Math.min(adjustScale * e.scale, 4));
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
var scaledX = ((((image.width * currentScale) / 2) - (image.width / 2)) / currentScale);
if (currentDeltaX > scaledX)
currentDeltaX = scaledX;
if (currentDeltaX < -scaledX)
currentDeltaX = -scaledX;
var scaledY = ((((image.height * currentScale) / 2) - (image.height / 2)) / currentScale);
if (currentDeltaY > scaledY)
currentDeltaY = scaledY;
if (currentDeltaY < -scaledY)
currentDeltaY = -scaledY;
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('panend pinchend', function () {
adjustScale = currentScale;
adjustDeltaX = currentDeltaX;
adjustDeltaY = currentDeltaY;
});
resets[i] = function reset() {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
currentScale = null;
currentDeltaX = null;
currentDeltaY = null;
image.style.transform = 'scale(' + 1 + ') translate3d(' + 0 + 'px, ' + 0 + 'px, 0)';
}
})(i);
}
}

Related

javascript function works with after load changes

i have a javascript scroll function and it will detect elements with section class and add them to fullpage scroll. at first i have only 2 elements with section class but after clicking on a button jQuery add a new div with section class now i should have 3 fullpage instead of 2. here is the structure of my code:
(function () {
'use strict';
/**
* Full scroll main function
*/
var fullScroll = function (params) {
/**
* Main div
* #type {Object}
*/
var main = document.getElementById(params.mainElement);
/**
* Sections divclass
* #type {Array}
*/
var sections = main.getElementsByClassName('section');
/**
* Full page scroll configurations
* #type {Object}
*/
var defaults = {
container: main,
sections: sections,
animateTime: params.animateTime || 0.7,
animateFunction: params.animateFunction || 'ease',
maxPosition: sections.length - 1,
currentPosition: 0,
displayDots: typeof params.displayDots != 'undefined' ? params.displayDots : true,
dotsPosition: params.dotsPosition || 'left'
};
this.defaults = defaults;
/**
* Init build
*/
this.init();
};
/**
* Init plugin
*/
fullScroll.prototype.init = function () {
this.buildPublicFunctions()
.buildSections()
.buildDots()
.addEvents();
var anchor = location.hash.replace('#', '').split('/')[0];
location.hash = 0;
this.changeCurrentPosition(anchor);
this.registerIeTags();
};
/**
* Build sections
* #return {Object} this(fullScroll)
*/
fullScroll.prototype.buildSections = function () {
var sections = this.defaults.sections;
for (var i = 0; i < sections.length; i++) {
sections[i].setAttribute('data-index', i);
}
return this;
};
/**
* Build dots navigation
* #return {Object} this (fullScroll)
*/
fullScroll.prototype.buildDots = function () {
this.ul = document.createElement('ul');
this.ul.className = this.updateClass(1, 'dots', this.ul.className);
this.ul.className = this.updateClass(1, this.defaults.dotsPosition == 'right' ? 'dots-right' : 'dots-left', this.ul.className);
var _self = this;
var sections = this.defaults.sections;
for (var i = 0; i < sections.length; i++) {
var li = document.createElement('li');
var a = document.createElement('a');
a.setAttribute('href', '#' + i);
li.appendChild(a);
_self.ul.appendChild(li);
}
this.ul.childNodes[0].firstChild.className = this.updateClass(1, 'active', this.ul.childNodes[0].firstChild.className);
if (this.defaults.displayDots) {
document.body.appendChild(this.ul);
}
return this;
};
/**
* Add Events
* #return {Object} this(fullScroll)
*/
fullScroll.prototype.addEvents = function () {
if (document.addEventListener) {
document.addEventListener('mousewheel', this.mouseWheelAndKey, false);
document.addEventListener('wheel', this.mouseWheelAndKey, false);
document.addEventListener('keyup', this.mouseWheelAndKey, false);
document.addEventListener('touchstart', this.touchStart, false);
document.addEventListener('touchend', this.touchEnd, false);
window.addEventListener("hashchange", this.hashChange, false);
/**
* Enable scroll if decive don't have touch support
*/
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
if (!('ontouchstart' in window)) {
document.body.style = "overflow: scroll;";
document.documentElement.style = "overflow: scroll;";
}
}
} else {
document.attachEvent('onmousewheel', this.mouseWheelAndKey, false);
document.attachEvent('onkeyup', this.mouseWheelAndKey, false);
}
return this;
};
/**
* Build public functions
* #return {[type]} [description]
*/
fullScroll.prototype.buildPublicFunctions = function () {
var mTouchStart = 0;
var mTouchEnd = 0;
var _self = this;
this.mouseWheelAndKey = function (event) {
if (event.deltaY > 0 || event.keyCode == 40) {
_self.defaults.currentPosition++;
_self.changeCurrentPosition(_self.defaults.currentPosition);
} else if (event.deltaY < 0 || event.keyCode == 38) {
_self.defaults.currentPosition--;
_self.changeCurrentPosition(_self.defaults.currentPosition);
}
_self.removeEvents();
};
this.touchStart = function (event) {
mTouchStart = parseInt(event.changedTouches[0].clientY);
mTouchEnd = 0;
};
this.touchEnd = function (event) {
mTouchEnd = parseInt(event.changedTouches[0].clientY);
if (mTouchEnd - mTouchStart > 100 || mTouchStart - mTouchEnd > 100) {
if (mTouchEnd > mTouchStart) {
_self.defaults.currentPosition--;
} else {
_self.defaults.currentPosition++;
}
_self.changeCurrentPosition(_self.defaults.currentPosition);
}
};
this.hashChange = function (event) {
if (location) {
var anchor = location.hash.replace('#', '').split('/')[0];
if (anchor !== "") {
if (anchor < 0) {
_self.changeCurrentPosition(0);
} else if (anchor > _self.defaults.maxPosition) {
_self.changeCurrentPosition(_self.defaults.maxPosition);
} else {
_self.defaults.currentPosition = anchor;
_self.animateScroll();
}
}
}
};
this.removeEvents = function () {
if (document.addEventListener) {
document.removeEventListener('mousewheel', this.mouseWheelAndKey, false);
document.removeEventListener('wheel', this.mouseWheelAndKey, false);
document.removeEventListener('keyup', this.mouseWheelAndKey, false);
document.removeEventListener('touchstart', this.touchStart, false);
document.removeEventListener('touchend', this.touchEnd, false);
} else {
document.detachEvent('onmousewheel', this.mouseWheelAndKey, false);
document.detachEvent('onkeyup', this.mouseWheelAndKey, false);
}
setTimeout(function () {
_self.addEvents();
}, 600);
};
this.animateScroll = function () {
var animateTime = this.defaults.animateTime;
var animateFunction = this.defaults.animateFunction;
var position = this.defaults.currentPosition * 100;
this.defaults.container.style.webkitTransform = 'translateY(-' + position + 'vh)';
this.defaults.container.style.mozTransform = 'translateY(-' + position + 'vh)';
this.defaults.container.style.msTransform = 'translateY(-' + position + 'vh)';
this.defaults.container.style.transform = 'translateY(-' + position + 'vh)';
this.defaults.container.style.webkitTransition = 'all ' + animateTime + 's ' + animateFunction;
this.defaults.container.style.mozTransition = 'all ' + animateTime + 's ' + animateFunction;
this.defaults.container.style.msTransition = 'all ' + animateTime + 's ' + animateFunction;
this.defaults.container.style.transition = 'all ' + animateTime + 's ' + animateFunction;
for (var i = 0; i < this.ul.childNodes.length; i++) {
this.ul.childNodes[i].firstChild.className = this.updateClass(2, 'active', this.ul.childNodes[i].firstChild.className);
if (i == this.defaults.currentPosition) {
this.ul.childNodes[i].firstChild.className = this.updateClass(1, 'active', this.ul.childNodes[i].firstChild.className);
}
}
};
this.changeCurrentPosition = function (position) {
if (position !== "") {
_self.defaults.currentPosition = position;
location.hash = _self.defaults.currentPosition;
}
};
this.registerIeTags = function () {
document.createElement('section');
};
this.updateClass = function (type, newClass, currentClass) {
if (type == 1) {
return currentClass += ' ' + newClass;
} else if (type == 2) {
return currentClass.replace(newClass, '');
}
};
return this;
};
window.fullScroll = fullScroll;
})();
scrollFunc = new fullScroll({
mainElement: 'scrollProduct',
displayDots: false,
animateTime: 0.7,
animateFunction: 'ease'
});
1
2

JW Player - Amazon Web Services CDN and Advanced Javascript Debugging

I have a customized JW Player 7 Pro embedded on the following page: http://dev.sharepoint-videos.com/jw-player-self-hosted/.
The embed code is as follows:
<!--Course Video, Scripts and Style-->
<div id="visualSPPlayer">Loading the player...</div>
<script type="text/javascript">
var playerInstance = jwplayer("visualSPPlayer");
playerInstance.setup({
file: "http://dbt8c2ssdzlxg.cloudfront.net/Search2013.mp4",
primary: "HTML5",
image: "https://assets-jpcust.jwpsrv.com/thumbs/2kOAeo0k-320.jpg?1443200073230",
width: "100%",
aspectratio: "16:9",
tracks: [
{
file: "http://dbt8c2ssdzlxg.cloudfront.net/captions/Search/Captions.srt",
label: "English",
kind: "captions",
},
{
file: 'http://dbt8c2ssdzlxg.cloudfront.net/chapters/Search/Chapters.vtt',
kind: 'chapters'
},
{
file: "http://dbt8c2ssdzlxg.cloudfront.net/thumbnails/search_thumbnails.vtt",
kind: "thumbnails"
}
],
skin: {
name: "vapor",
active: "#E16933",
inactive: "#E16933",
background: "#333333"
}
});
</script>
<script type="application/javascript" src="http://dev.sharepoint-videos.com/wp-content/themes/symplex-child/js/player.js"></script>
<link rel="stylesheet" href="http://dev.sharepoint-videos.com/wp-content/themes/symplex-child/css/player.css" type="text/css" media="screen"/>
The player.js file contents:
jQuery(document).ready(function () {
jQuery(function ($) {
var playerInstance = jwplayer();
var chapters = [];
var captions = [];
var toc = [];
var caption = -1;
var matches = [];
var seekArr = [];
var seekPos = [];
var seePos;
var query = "";
var cycle = -1;
var transcript = document.getElementById('courseTranscript');
var search = document.getElementById('courseSearch');
var match = document.getElementById('courseMatch');
var caption_file;
var chapter_file;
playerInstance.onReady(function () {
//Self-Hosted
caption_file = playerInstance.getPlaylist()[0].tracks[0].file;
chapter_file = playerInstance.getPlaylist()[0].tracks[1].file;
if (playerInstance.getRenderingMode() == "flash") {
return;
}
tag = document.querySelector('video');
tag.defaultPlaybackRate = 1.0;
tag.playbackRate = 1.0;
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/hare.png", "1.5x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 1.5;
}, "playerHighSpeed");
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/normal.png", "1.0x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 1.0;
}, "playerNormalSpeed");
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/snail.png", "0.5x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 0.5;
}, "playerSlowSpeed");
});
//Adds Player Focus on Playing
playerInstance.on('play', function () {
$('html, body').animate({
scrollTop: $(".jwplayer").offset().top - 190
}, 1000);
});
playerInstance.onReady(function () {
$.get(caption_file, function (data) {
data = data.trim();
var t = data.split("\n\r\n");
for (var i = 0; i < t.length; i++) {
var c = parse(t[i]);
chapters.push(c);
}
loadCaptions();
loadChapters();
});
//
});
// Load chapters / captions
function loadCaptions() {
$.get(caption_file, function (data) {
data = data.trim();
var t = data.split("\n\r\n");
t.pop();
var h = "<p>";
var s = 0;
for (var i = 0; i < t.length; i++) {
var c = parse(t[i]);
if (s < chapters.length && c.begin > chapters[s].begin) {
s++;
}
h += "<span id='caption" + i + "'>" + c.text + "</span>";
captions.push(c);
}
transcript.innerHTML = h + "</p>";
});
};
function parse(d) {
var a = d.split("\n");
//console.log(a[1]);
var i = a[1].indexOf(' --> ');
var t = a[2]; //Caption text
if (a[3]) {
t += " " + a[3];
}
t = t.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return {
begin: seconds(a[1].substr(0, i)),
btext: a[1].substr(3, i - 7),
end: seconds(a[1].substr(i + 5)),
text: t
}
};
function seconds(s) {
var a = s.split(':');
secs = a[2].substring(0, a[2].indexOf(','));
var r = Number(secs) + Number(a[a.length - 2]) * 60;
if (a.length > 2) {
r += Number(a[a.length - 3]) * 3600;
}
return r;
};
function toc_seconds(s) {
var a = s.split(':');
secs = a[2].substring(0, a[2].indexOf('.'));
var r = Number(secs) + Number(a[a.length - 2]) * 60;
if (a.length > 2) {
r += Number(a[a.length - 3]) * 3600;
}
return r;
};
function toc_time(s) {
var a = s.split(':');
var ms = a[2].split(".");
var h = a[0];
if (h != "00") {
var r = a[0] + ":" + a[1] + ":" + ms[0];
} else {
var r = a[1] + ":" + ms[0];
}
return r;
};
// Highlight current caption and chapter
playerInstance.onTime(function (e) {
var p = e.position;
for (var j = 0; j < captions.length; j++) {
if (captions[j].begin < p && captions[j].end > p) {
if (j != caption) {
var c = document.getElementById('caption' + j);
if (caption > -1) {
document.getElementById('caption' + caption).className = "";
}
c.className = "current";
if (query == "") {
transcript.scrollTop = c.offsetTop - transcript.offsetTop - 40;
}
caption = j;
}
break;
}
}
});
// Hook up interactivity
transcript.addEventListener("click", function (e) {
if (e.target.id.indexOf("caption") == 0) {
var i = Number(e.target.id.replace("caption", ""));
playerInstance.seek(captions[i].begin);
}
});
/**/
search.addEventListener('focus', function (e) {
setTimeout(function () {
search.select();
}, 100);
resetSearch();
$("#prevMatchLink").hide();
$("#nextMatchLink").hide();
});
search.addEventListener('keydown', function (e) {
if (e.keyCode == 27) {
resetSearch();
$("#prevMatchLink").hide();
$("#nextMatchLink").hide();
} else if (e.keyCode == 13) {
$("#prevMatchLink").show();
$("#nextMatchLink").show();
var q = this.value.toLowerCase();
if (q.length > 0) {
if (q == query) {
if (cycle >= matches.length - 1) {
cycleSearch(0);
} else {
cycleSearch(cycle + 1);
}
} else {
resetSearch();
searchTranscript(q);
}
} else {
resetSearch();
}
} else if (e.keyCode == 37) {
cycleSearch(cycle - 1);
}
else if (e.keyCode == 39) {
cycleSearch(cycle + 1);
}
});
$("#prevMatchLink").click(function (e) {
e.preventDefault();
cycleSearch(cycle - 1);
});
$("#nextMatchLink").click(function (e) {
e.preventDefault();
cycleSearch(cycle + 1);
});
// Execute search
function searchTranscript(q) {
matches = [];
query = q;
for (var i = 0; i < captions.length; i++) {
var m = captions[i].text.toLowerCase().indexOf(q);
if (m > -1) {
document.getElementById('caption' + i).innerHTML =
captions[i].text.substr(0, m) + "<em>" +
captions[i].text.substr(m, q.length) + "</em>" +
captions[i].text.substr(m + q.length);
matches.push(i);
}
}
if (matches.length) {
cycleSearch(0);
} else {
resetSearch();
}
};
function cycleSearch(i) {
if (cycle > -1) {
var o = document.getElementById('caption' + matches[cycle]);
o.getElementsByTagName("em")[0].className = "";
}
var c = document.getElementById('caption' + matches[i]);
c.getElementsByTagName("em")[0].className = "current";
match.innerHTML = (i + 1) + " of " + matches.length;
transcript.scrollTop = c.offsetTop - transcript.offsetTop - 40;
cycle = i;
};
function resetSearch() {
if (matches.length) {
for (var i = 0; i < captions.length; i++) {
document.getElementById('caption' + i).innerHTML = captions[i].text;
}
}
query = "";
matches = [];
match.innerHTML = "0 of 0";
cycle = -1;
transcript.scrollTop = 0;
};
var videoTitle = $(".videoTitle").text();
var hasPlayed = false;
playerInstance.onBeforePlay(function (event) {
if (hasPlayed == false) {
ga('send', 'event', 'Video', 'Play', videoTitle);
hasPlayed = true;
}
});
//Can be used to trigger the Course to Marked Completed so the user doesn't have to
playerInstance.on('complete', function () {
});
function loadChapters() {
$.get(chapter_file, function (data) {
data = data.trim();
var c = data.split("\n\r\n");
var d;
for (var i = 0; i < c.length; i++) {
d = c[i].split("\n");
//pushes in Title for each chapter
toc.push(d[0]);
//pushes in the time intervals for each chapter
seekArr.push(d[1]);
};
for (var a = 0; a < seekArr.length; a++) {
//Splits the time interval and pushes the start interval for each chapter
var tempPos = seekArr[a].split(" --> ");
seekPos.push(tempPos[0]);
};
runTOC(seekPos);
var toc_output = "";
$.each(toc, function (i, v) {
toc_output += "<li class=ch" + i + "><a href='#' onclick='jwplayer().seek(" + toc_seconds(seekPos[i]) + ");'>" + v + "</a> (" + toc_time(seekPos[i]) + ")</li>"
});
if (toc.length < 7) {
toc_output += " <li class='blank'> </li><li class='blank'> </li>";
}
$(".courseTitles ul").html(toc_output);
});
};
function runTOC(x) {
playerInstance.onTime(function (event) {
for (var i = 0; i < x.length; i++) {
if (event.position > toc_seconds(x[i])) {
$(".courseTitles ul li").removeClass("active");
$(".courseTitles ul li.ch" + i).addClass('active');
}
};
});
}
});
});
We are hosting the video and Chapter/Captions VTT files using Amazon Web Services with Cloudfront.
We have included the interactive transcript from the captions as well as dynamic video chapters to be loaded once the video is ready to be played.
One thing I have noticed is that the chapters and the transcript do not always load and require the page to be refreshed several times so I was thinking that maybe it was a caching issue on the AWS side of the equation.
I have used Google Chrome and there are no errors in the developers console when the chapters and transcript do not load.
It should be noted that this functionality was working flawlessly when were using the JW Platform cloud hosted solution so it seems to be a factor of the AWS/Cloudfront CDN.
function load_jwp_scripts() {
wp_enqueue_script('jwplayer-js', plugins_url( "/js/jwplayer.js", __FILE__), array(), '1.0', false);
wp_enqueue_script('jwplayer-license-js', plugins_url( "/js/jwplayer_license.js", __FILE__), array(), '1.0', false);
wp_enqueue_script('jwplayer-player-js', plugins_url( "/js/player.js", __FILE__), array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'load_jwp_scripts');
I was able to find a workable solution to my problem.
The issue was the use of the $(document).ready declaration. It is not compatible with jwplayer.on("ready").
Removing that and it is rendering properly again.

how to make synchronous call to json data from angularjs

I am calling some data from a JSON file in AngularJS but due to the asynchronous call the code is moving to other step before receiving the data so that is causing an error.
I used $http.get
$http.get('job.json').success(function (response) {
$scope.big = response;
});
Can you suggest some synchronous method to call json data which is
{
"days": [{
"dayname": "Sun,23 Aug 2015",
"date": "2015-08-23",
"hours": "hoursArray(array24)"
}, {
"dayname": "Mon,24 Aug 2015",
"date": "2015-08-24",
"hours": "hoursArray(array24)"
}, {
"dayname": "Tue,25 Aug 2015",
"date": "2015-08-25",
"hours":"hoursArray(array24)"
}, {
"dayname": "Wed,26 Aug 2015",
"date": "2015-08-26",
"hours": "hoursArray(array24)"
}]
}
this is the jquery file i am using
(function($) {
$.fn.schedule = function(options) {
var methods = {
init : function(ele, opt) {
//methods.currentdate = methods.now.getFullYear() + "Engine Change" + methods.now.getMonth() + "Engine Change" + methods.now.getDate();
methods.currentdate = methods.now.getFullYear() + "-" + methods.now.getMonth() + "-" + methods.now.getDate();
// $("#scheduleAllDays > *").each(function(){
// var item = $(this);
// $("#scheduleAllDays").width($("#scheduleAllDays").width()+item.width());
// });
// $("#scheduleAllDays").width($("#scheduleAllDays").width());
ele.find("[data-row]").each(function() {
var drow = $(this), drowset = $("[data-row='" + drow.data("row") + "']");
var maxheight = methods.elesMaxHeight(drowset);
drowset.height(maxheight);
});
methods.allocateDurations(ele);
$("#scheduleContentInner", ele).css("min-height", $(".schedule-drag-wrap", ele).innerHeight());
},
elesMaxHeight : function(ele) {
var heights = $(ele).map(function() {
return $(this).height();
}).get();
return Math.max.apply(null, heights);
},
allocateDurations : function(ele) {
methods.flightdata = {
routes : {}
};
ele.find("[data-flight-row]").each(function(i, ival) {
var flight = $(this);
methods.flightdata.routes["row" + i] = [];
flight.find("[data-flight-record]").each(function() {
var currentFlight = $(this), flightrecord = methods.makeStringToObject(currentFlight.data("flight-record"));
flightrecord.element = currentFlight;
methods.flightdata.routes["row" + i].push(flightrecord);
});
});
methods.positionSet(ele);
},
positionSet : function(ele) {
var dayelement = $("#scheduleAllDays > *", ele);
var totaldaywidth = $("#scheduleAllDays").width() + 30;
var totaldays = dayelement.size();
var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var divider = $(".schedule-h-divider");
dayelement.each(function(i, ival) {
var dayele = $(this), dividerele = divider.eq(i);
dividerele.css({
top : $("#scheduleAllDays").height(),
left : dayele.offset().left - 104
});
});
for (var i in methods.flightdata.routes) {
var iobj = methods.flightdata.routes[i];
for (var j in iobj) {
var jobj = iobj[j];
var duration = jobj.duration, width = Number(methods.hmtosec(duration, ".") * perSecondsWidth);
var parent = jobj.element.parent();
jobj.element.css({
// position : "relative",
width : width + "px",
overflow : "hidden",
"white-space" : "nowrap"
}).parent().css({
// width : width+"px",
// overflow : "hidden"
// position:"absolute",
left : (j==0)?0:parent.prev().position().left+parent.prev().width()
});
}
}
methods.dragInit(ele);
},
setCurrentTimeMarker : function(ele) {
var marker = $(".schedule-current-time-marker");
var markerpills = $(".schedule-time-marker-pills");
var dayelement = $("#scheduleAllDays > *", ele);
var totaldaywidth = $("#scheduleAllDays").width() + 30;
var totaldays = dayelement.size();
var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var currentdate = new Date();
var format = currentdate.getFullYear() + "Engine Change" + currentdate.getMonth() + "Engine Change" + currentdate.getDate();
var currentdateele = $("#scheduleAllDays").find("[data-date='" + format + "']");
var days = (currentdateele.index()), seconds = ((days * 24) * 60) * 60;
seconds = seconds + methods.hmtosec(currentdate.getHours() + "." + currentdate.getMinutes(), ".");
marker.stop().animate({
top : $("#scheduleAllDays",ele).height()-53,
left : (seconds * perSecondsWidth) - (marker.width() / 2)
}, 1000, "swing");
markerpills.html(currentdate.getHours() + ":" + currentdate.getMinutes());
methods.markermove = setInterval(function() {
currentdate = new Date();
marker.css({
left : marker.position().left + perSecondsWidth
}, "fast", "swing");
markerpills.html(methods.makezerodigit(currentdate.getHours()) + " : " + methods.makezerodigit(currentdate.getMinutes()));
// methods.schedulemove(ele,perSecondsWidth);
}, 1000);
},
schedulemove : function(ele,seconds) {
var dragwrap = ele.find(".schedule-drag-wrap");
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragwrap.width() - ($(window).width() - routewidth));
if (Math.abs(dragwrap.position().left) < Math.abs(maxleft)) {
dragwrap.css({
left : (dragwrap.position().left - (dragwrap.width)) + "px"
});
}
},
makezerodigit : function(digit) {
return (String(digit).match(/^[0-9]$/)) ? "0" + digit : digit;
},
dragInit : function(ele) {
var currentdaycol = $("[data-date='" + methods.currentdate + "']");
ele.find(".schedule-drag-wrap").css({
left : -(currentdaycol.position().left - 50) + "px"
}).animate({
left : -currentdaycol.position().left - 0 + "px"
}, 1000, "swing", function() {
methods.drag(ele);
methods.setCurrentTimeMarker(ele);
});
},
drag : function(ele) {
methods.move = null;
$(".schedule-drag-wrap", ele).on("mousedown", function(e) {
var dragele = $(this), position = dragele.position();
methods.move = {
x : e.pageX,
y : e.pageY,
left : position.left
};
}).on("mouseup mouseleave", function(e) {
var dragele = $(this);
if (methods.move) {
methods.move = null;
dragele.removeClass("userselect-none cursor-move");
}
}).on("mousemove", function(e) {
var dragele = $(this), position = dragele.position(), movedx, drag = true;
if (methods.move) {
methods.curmove = {
x : e.pageX,
y : e.pageY
};
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragele.width() - ($(window).width() - routewidth));
var xcondition = (methods.move.x > methods.curmove.x);
dragele.addClass("userselect-none cursor-move");
if (position.left <= maxleft && xcondition) {
drag = false;
dragele.css({
left : maxleft
});
}
if (position.left > -10 && !xcondition) {
drag = false;
dragele.css({
left : 0
});
}
if (drag) {
//if direction right to left
movedx = methods.move.left + (methods.curmove.x - methods.move.x);
dragele.css({
left : movedx
});
}
}
});
},
now : new Date(),
currentdate : "",
hmtosec : function(hours, identy) {
var s = (hours.match(/\./)) ? hours.split(identy) : [hours, 0], h = s[0], m = s[1];
h = (Number(h)) ? (h * 60) * 60 : 0;
m = (m == 0) ? 0 : m * 60;
return Number(h + m);
},
makeStringToObject : function(string) {
var loc_string = String(string).split("|");
var output = {};
for (var i in loc_string) {
var keyvalue = loc_string[i].split("~");
output[keyvalue[0]] = keyvalue[1];
}
return output;
}
};
return this.each(function() {
methods.init($(this), $.extend({}, $.fn.schedule.setting, options));
});
};
$.fn.schedule.setting = {};
})(jQuery);
and this is the error i am getting
Uncaught TypeError: Cannot read property 'left' of undefined
In service: var deferred = $q.defer();
$http.get('job.json')
.success(function(response) {
defer.resolve(response);
}).error(function(error){
console.log(error);
})
return deferred.promise;
In controller:
var p=<serviceCall>
p.then(function(s){
$scope.ans=s;
})
The $q is used for getting synchronous response.for more details:https://docs.angularjs.org/api/ng/service/$q
You can't do a synchronous HTTP request, since the reponse (in your case it is the JSON file) can not be loaded instantly. However, $http.get returns a promise which is resolved when the request completes. You should do everything you want to do as soon as the JSON file has loaded inside the then-block of the promise.
$http.get('job.json').then(function (response) {
$scope.big = response;
// Do anything else you need to after JSON has been loaded.
});
Using promise.then you can update your value.
var promise=$http.get('job.json');
promise.then(function(result){
$scope.big=response;
});
alternative way
function getObj(callback){
$http.get('job.json').success(callback);;
}
getObj(function(result){
console.log(result)
// add your jquery code
})

Stop function on dialog open

have a question for you. I am loading a function that I want to stop once they click the sprite, which in turn opens a dialog.
How can I do this?
My jQuery to make a image pop up in specific coordinates:
(function fadeInDiv(){
var divs = $('#showSprite');
var fadeInTime = Math.floor(Math.random()*(3000-1000+1)+1000);
var fadeOutTime = Math.floor(Math.random()*(5000-1000+1)+1000);
var timeThere = Math.floor(Math.random()*(50-25+1)+25);
var elem = divs.eq(Math.floor(Math.random()*divs.length));
var whichCord = Math.floor(Math.random()*(6-1+1)+1);
var arrayDictionary = {
ary1: ["39","141"],
ary2: ["85","27"],
ary3: ["215","166"],
ary4: ["351","13"],
ary5: ["389","168"],
ary6: ["486","32"],
ary7: ["576","150"]
};
if (!elem.is(':visible')) {){
elem.fadeIn(Math.floor(Math.random()*fadeInTime),fadeInDiv);
elem.css({
'position':'absolute',
'left':arrayDictionary["ary"+whichCord][0]+'px',
'top':arrayDictionary["ary"+whichCord][1]+'px'
});
}
else {
elem.fadeOut(Math.floor(Math.random()*fadeOutTime),fadeInDiv)
.delay(timeThere);
}
})();
and my dialog:
$('#clickedSprite').dialog({
autoOpen: false,
title: 'What Do We Have Here?'
});
$('#sprite').click(function() {
var palID = $(this).attr('palID');
var petID = $(this).attr('petID');
var securePass = $(this).attr('securePass');
var timePassed = new Date().getTime() / 1000;
$.cookie("hashing", securePass);
$.cookie("timePassed", Math.round(timePassed));
$('#clickedSprite').dialog('open');
return false;
});
Use !$(".ui-dialog").length to check that there are no dialogs:
(function fadeInDiv() {
if(!$(".ui-dialog").length){
var divs = $('#showSprite');
var fadeInTime = Math.floor(Math.random() * (3000 - 1000 + 1) + 1000);
var fadeOutTime = Math.floor(Math.random() * (5000 - 1000 + 1) + 1000);
var timeThere = Math.floor(Math.random() * (50 - 25 + 1) + 25);
var elem = divs.eq(Math.floor(Math.random() * divs.length));
var whichCord = Math.floor(Math.random() * (6 - 1 + 1) + 1);
var arrayDictionary = {
ary1: ["39", "141"],
ary2: ["85", "27"],
ary3: ["215", "166"],
ary4: ["351", "13"],
ary5: ["389", "168"],
ary6: ["486", "32"],
ary7: ["576", "150"]
};
if (!elem.is(':visible')) {) {
elem.fadeIn(Math.floor(Math.random() * fadeInTime), fadeInDiv);
elem.css({
'position': 'absolute',
'left': arrayDictionary["ary" + whichCord][0] + 'px',
'top': arrayDictionary["ary" + whichCord][1] + 'px'
});
} else {
elem.fadeOut(Math.floor(Math.random() * fadeOutTime), fadeInDiv)
.delay(timeThere);
}
}
})();

Popunder script that works on all mobiles

I have tested around 15 different popunder scripts to find one that works on all mobiles. The following script is the best one I've found and works perfectly on my Galaxy S3 but annoyingly pops-over on a Galaxy S5. I need the script to popunder on any action on the screen, so that it opens in the background without interfering with the current page. This script has everything I need aside from the fact it behaves differently depending on what Android device it's run on. Can anyone please assist in editing this JavaScript code so it pops-under on all Android browsers and not just some?
Here is the code:
var puShown = false;
var PopWidth = 1370;
var PopHeight = 800;
var PopFocus = 0;
var _Top = null;
function GetWindowHeight() {
var myHeight = 0;
if (typeof(_Top.window.innerHeight) == 'number') {
myHeight = _Top.window.innerHeight;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientHeight) {
myHeight = _Top.document.documentElement.clientHeight;
} else if (_Top.document.body && _Top.document.body.clientHeight) {
myHeight = _Top.document.body.clientHeight;
}
return myHeight;
}
function GetWindowWidth() {
var myWidth = 0;
if (typeof(_Top.window.innerWidth) == 'number') {
myWidth = _Top.window.innerWidth;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientWidth) {
myWidth = _Top.document.documentElement.clientWidth;
} else if (_Top.document.body && _Top.document.body.clientWidth) {
myWidth = _Top.document.body.clientWidth;
}
return myWidth;
}
function GetWindowTop() {
return (_Top.window.screenTop != undefined) ? _Top.window.screenTop : _Top.window.screenY;
}
function GetWindowLeft() {
return (_Top.window.screenLeft != undefined) ? _Top.window.screenLeft : _Top.window.screenX;
}
function doOpen(url) {
var popURL = "about:blank"
var popID = "ad_" + Math.floor(89999999 * Math.random() + 10000000);
var pxLeft = 0;
var pxTop = 0;
pxLeft = (GetWindowLeft() + (GetWindowWidth() / 2) - (PopWidth / 2));
pxTop = (GetWindowTop() + (GetWindowHeight() / 2) - (PopHeight / 2));
if (puShown == true) {
return true;
}
var PopWin = _Top.window.open(popURL, popID, 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,top=' + pxTop + ',left=' + pxLeft + ',width=' + PopWidth + ',height=' + PopHeight);
if (PopWin) {
puShown = true;
if (PopFocus == 0) {
PopWin.blur();
if (navigator.userAgent.toLowerCase().indexOf("applewebkit") > -1) {
_Top.window.blur();
_Top.window.focus();
}
}
PopWin.Init = function(e) {
with(e) {
Params = e.Params;
Main = function() {
if (typeof window.mozPaintCount != "undefined") {
var x = window.open("about:blank");
x.close();
}
var popURL = Params.PopURL;
try {
opener.window.focus();
} catch (err) {}
window.location = popURL;
}
Main();
}
};
PopWin.Params = {
PopURL: url
}
PopWin.Init(PopWin);
}
return PopWin;
}
function setCookie(name, value, time) {
var expires = new Date();
expires.setTime(expires.getTime() + time);
document.cookie = name + '=' + value + '; path=/;' + '; expires=' + expires.toGMTString();
}
function getCookie(name) {
var cookies = document.cookie.toString().split('; ');
var cookie, c_name, c_value;
for (var n = 0; n < cookies.length; n++) {
cookie = cookies[n].split('=');
c_name = cookie[0];
c_value = cookie[1];
if (c_name == name) {
return c_value;
}
}
return null;
}
function initPu() {
_Top = self;
if (top != self) {
try {
if (top.document.location.toString())
_Top = top;
} catch (err) {}
}
if (document.attachEvent) {
document.attachEvent('onclick', checkTarget);
} else if (document.addEventListener) {
document.addEventListener('click', checkTarget, false);
}
}
function checkTarget(e) {
if (!getCookie('popundr')) {
var e = e || window.event;
var win = doOpen('http://www.mediamoby.com/4g9s0hc8/');
setCookie('popundr', 1, 24 * 60 * 60 * 1000);
}
}
initPu();

Categories