please help to fix the script or tell me which direction to think.
There is a calculator for ordering goods:
$(function(){
var price = {
'130': {
'list': {
'a3': {
'4+4': {
'500': 3255,
'1000': 3720,
'2000': 4935,
'3000': 5935,
'4000': 6935,
},
'4+0': {
'500': 3031,
'1000': 3456,
'2000': 4410,
},
},
'a4': {
}
},
'flaer': {
}
},
'160': {
}
};
var dict = {
'130': '130 г/м²',
'160': '160 г/м²',
'list': 'Листовки',
'flaer': 'Флаеры',
}
var str = '',
multi;
// Selecting something by clicking a button
$(document).on('click', '#calc button', function(event){
//event.preventDefault();
$(this).parent().data('selected', $(this).data('id'));
$(this).addClass('selected').siblings().removeClass('selected');
$('#calc_result').empty();
var priceitem = price,
param;
for (var i=0; i < 5; i++)
{
param = $('#calc div:eq('+i+')').data('selected');
if (param)
priceitem = priceitem[param];
else
break;
}
if (i == 5)
{
$('#calc_result').text(priceitem);
q = $('button.selected');
q.each(function(){
str = str + $(this).text() + ', ';
})
str = str.substring(0, str.length - 2);
$('#calc_summary').append(str);
}
// shadow hide
$(this).closest('.cell').next().find('.cell_shadow').css('display', 'none');
});
// Pre-filling
var priceitem = price;
for (var lvl=0; lvl < 5; lvl++)
{
var iter = 0;
for (var i in priceitem)
{
if (!iter)
priceitem = priceitem[i]
iter++;
$('#calc .lvl'+lvl).append('<button data-id="'+i+'">'+((i in dict) ? dict[i] : i)+'</button>');
}
}
// multiplication request
$('#odin_plus').on('click', function(){
if($('#calc_multi').html() == ''){
multi = 1;
addMulti(multi);
}
else{
multi = multi + 1;
addMulti(multi);
};
$('#odin_minus').css('visibility', 'visible');
});
$('#odin_minus').on('click', function(){
if($('#calc_multi').html().substring(2) != '1'){
multi = multi - 1;
addMulti(multi);
}
else{
$('#odin_minus').css('visibility', 'hidden');
$('#calc_multi').html('');
};
});
function addMulti(multi){
$('#calc_multi').html(' x' + multi);
};
$('#listovki_submit').on('click', function(){
alert('Ваша заявка отправлена ' + '\n' + str + ' ' + $('#calc_multi').text());
});
});
the problem is that when choosing the next block. cell_13 contains 5 buttons.
choosing the next block. cell_13 also contains 5 buttons (but should contain three buttons!)
I need to for the case of "4 + 0" block. cell_13 contained 3 buttons
Related
I am making a JavaScript solution related to MediaWiki, but what it is for is not really needed information, so I will leave it there. I have the following function:
wgAjaxLicensePreview=true;
function getLicensePreview(num) {
console.log('glp num', num);
window.licenseSelectorCheck = function () {
var selector = document.getElementById("license" + num);
var selection = selector.options[selector.selectedIndex].value;
if (selector.selectedIndex > 0) {
if (selection == "") {
// Option disabled, but browser is broken and doesn't respect this
selector.selectedIndex = 0;
}
}
// We might show a preview
wgUploadLicenseObj.fetchPreview(selection);
};
var wpLicense = document.getElementById('license' + num);
console.log('glp wpLicense', wpLicense);
if (mw.config.get('wgAjaxLicensePreview') && wpLicense) {
// License selector check
wpLicense.onchange = licenseSelectorCheck;
// License selector table row
var wpLicenseRow = wpLicense.parentNode.parentNode;
var wpLicenseTbody = wpLicenseRow.parentNode;
var row = document.createElement('tr');
var td = document.createElement('td');
row.appendChild(td);
td = document.createElement('td');
td.id = 'mw-license-preview' + num;
row.appendChild(td);
wpLicenseTbody.insertBefore(row, wpLicenseRow.nextSibling);
console.log('glp row', row);
}
window.wgUploadLicenseObj = {
'responseCache': {
'': ''
},
'fetchPreview': function (license) {
if (!mw.config.get('wgAjaxLicensePreview'))
return;
for (cached in this.responseCache) {
console.log('glp fp responseCache', this.responseCache);
if (cached == license) {
this.showPreview(this.responseCache[license]);
return;
}
}
$('#license' + num).injectSpinner('license' + num);
var title = document.getElementById('imagename' + num).value;
if (!title)
title = 'File:Sample.jpg';
var url = mw.util.wikiScript('api')
+ '?action=parse&text={{' + encodeURIComponent(license) + '}}'
+ '&title=' + encodeURIComponent(title)
+ '&prop=text&pst&format=json';
var req = sajax_init_object();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
console.log('glp fp response', req.responseText);
wgUploadLicenseObj.processResult(eval('(' + req.responseText + ')'), license);
}
};
req.open('GET', url, true);
req.send('');
},
'processResult': function (result, license) {
$.removeSpinner('license' + num);
this.responseCache[license] = result['parse']['text']['*'];
console.log('glp pr result license', result, license);
this.showPreview(this.responseCache[license]);
},
'showPreview': function (preview) {
var previewPanel = document.getElementById('mw-license-preview' + num);
console.log('glp sp', previewPanel, preview, previewPanel.innerHTML == preview);
if (previewPanel.innerHTML != preview)
previewPanel.innerHTML = preview;
}
};
}
The issue with that, is the loop I have
var limit = this.max < this.fileCount ? this.max : this.fileCount;
console.log('glp', this.max, this.fileCount);
for (i = 1; i <= limit; i++) {
console.log('glp i', i);
getLicensePreview(i);
}
Does not iterate correctly for part of it, I have narrowed the issue down to, wpLicense.onchange = licenseSelectorCheck; which is rewriting the event handler to only check the last num.
Thanks to help from Barmar, I was able to solve this by making the wgUploadLicenseObj variable local rather then global window.wgUploadLicenseObj.
My final function ended up being:
wgAjaxLicensePreview=true;
function getLicensePreview(num) {
window.licenseSelectorCheck = function () {
var selector = document.getElementById("license" + num);
var selection = selector.options[selector.selectedIndex].value;
if (selector.selectedIndex > 0) {
if (selection == "") {
// Option disabled, but browser is broken and doesn't respect this
selector.selectedIndex = 0;
}
}
var wgUploadLicenseObj = {
'responseCache': {
'': ''
},
'fetchPreview': function (license) {
if (!mw.config.get('wgAjaxLicensePreview'))
return;
for (cached in this.responseCache) {
if (cached == license) {
this.showPreview(this.responseCache[license]);
return;
}
}
$('#license' + num).injectSpinner('license' + num);
var title = document.getElementById('imagename' + num).value;
if (!title)
title = 'File:Sample.jpg';
var url = mw.util.wikiScript('api')
+ '?action=parse&text={{' + encodeURIComponent(license) + '}}'
+ '&title=' + encodeURIComponent(title)
+ '&prop=text&pst&format=json';
var req = sajax_init_object();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
wgUploadLicenseObj.processResult(eval('(' + req.responseText + ')'), license);
}
};
req.open('GET', url, true);
req.send('');
},
'processResult': function (result, license) {
$.removeSpinner('license' + num);
this.responseCache[license] = result['parse']['text']['*'];
this.showPreview(this.responseCache[license]);
},
'showPreview': function (preview) {
var previewPanel = document.getElementById('mw-license-preview' + num);
if (previewPanel.innerHTML != preview)
previewPanel.innerHTML = preview;
}
};
// We might show a preview
wgUploadLicenseObj.fetchPreview(selection);
};
var wpLicense = document.getElementById('license' + num);
if (mw.config.get('wgAjaxLicensePreview') && wpLicense) {
// License selector check
wpLicense.onchange = licenseSelectorCheck;
// License selector table row
var wpLicenseRow = wpLicense.parentNode.parentNode;
var wpLicenseTbody = wpLicenseRow.parentNode;
var row = document.createElement('tr');
var td = document.createElement('td');
row.appendChild(td);
td = document.createElement('td');
td.id = 'mw-license-preview' + num;
row.appendChild(td);
wpLicenseTbody.insertBefore(row, wpLicenseRow.nextSibling);
}
}
I have a simple calculator made in JS and works well, but when I finish my calculation and get my result (i.e. pressing the "=" button), I want the returned result to be in a saved state. The "=" button must be ready to be clicked again, and get the same result, and then add it to the save result.
I've tried many obvious ways, such as adding the result to itself (which doesn't work because the result will be multiplied by itself, not added), exploiting the eval() function and adding a "+" string to the end result, etc.
TLDR: If you go to any calculator program, and type "2+2" and click equals, you get 4. If you click equals again, you get 6 ("2+2+2").
Here's my current code:
var disp = document.getElementById("calc-output"),
acceptedInputs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "-", ".", "+", "*", "/"];
function ud(n) {
if (acceptedInputs.includes(n)) {
if (disp.innerHTML.length == 31) {
disp.innerHTML = 0;
}
if (disp.innerHTML.length < 18) {
if (disp.innerHTML != 0) {
disp.innerHTML += n;
} else if (acceptedInputs.slice(11, -1).includes(n)) {
disp.innerHTML = 0 + n;
} else if (disp.innerHTML.toString().slice(1, 2) == ".") {
if (disp.innerHTML.toString().split(".").length-1 <= 1) {
disp.innerHTML += n;
}
} else {
disp.innerHTML = n;
}
}
}
}
function answer() {
if (eval(disp.innerHTML) == disp.innerHTML) {
disp.innerHTML = disp.innerHTML + "+"
}
c = eval(disp.innerHTML);
disp.innerHTML = c;
}
function clear() {
disp.innerHTML = "0";
}
function back() {
var str = disp.innerHTML.toString();
if (disp.innerHTML != 0 || str.charAt(1) == ".") {
if (str.length >= 2) {
str = str.slice(0, -1);
disp.innerHTML = str;
} else {
disp.innerHTML = 0;
}
}
}
document.getElementById("n1").addEventListener("click", function() {
ud(1);
});
document.getElementById("n2").addEventListener("click", function() {
ud(2);
});
document.getElementById("n3").addEventListener("click", function() {
ud(3);
});
document.getElementById("n4").addEventListener("click", function() {
ud(4);
});
document.getElementById("n5").addEventListener("click", function() {
ud(5);
});
document.getElementById("n6").addEventListener("click", function() {
ud(6);
});
document.getElementById("n7").addEventListener("click", function() {
ud(7);
});
document.getElementById("n8").addEventListener("click", function() {
ud(8);
});
document.getElementById("n9").addEventListener("click", function() {
ud(9);
});
document.getElementById("zero-button").addEventListener("click", function() {
ud(0);
});
document.getElementById("comma-button").addEventListener("click", function() {
ud('.');
});
document.getElementById("plus-button").addEventListener("click", function() {
ud('+');
});
document.getElementById("minus-button").addEventListener("click", function() {
ud('-');
});
document.getElementById("multi-button").addEventListener("click", function() {
ud('*');
});
document.getElementById("div-button").addEventListener("click", function() {
ud('/');
});
document.getElementById("back-button").addEventListener("click", function() {
back();
});
document.getElementById("clear-button").addEventListener("click", function() {
clear();
});
document.getElementById("equals-button").addEventListener("click", function() {
answer();
});
Save the last operation (e.g. " + 2") in some variable when user clicks equal. So, when he clicks again, just append saved value to the string from display.
var lastOperation = null;
function answer() {
if (eval(disp.innerHTML) == disp.innerHTML) {
// apply the last operation to displayed number
disp.innerHTML = disp.innerHTML + (lastOperation ? lastOperation[0] : '');
}
// find the last operation + | - | * | /
lastOperation = disp.innerHTML.split(new RegExp('(\\+|\\-|\\*|/).*$'));
c = eval(disp.innerHTML);
disp.innerHTML = c;
}
I currently have a javascript application that plays a couple of videos and asks a series of questions, based on the wait time in each question.
However, after a new video is triggered (2th video), my code skips the first question and I can't really find out why. Any ideas? Thank you.
Settings.js
var settings = {
'appname': 'ExperimentX',
'masterpassword': 'xxxx'
};
var videos = [
{
'video': 'movie 1.mp4',
'questions': [
{
'text': `
blabla
`,
'wait': 2 * 60 + 51
},
{
'text': 'How sad are you right now',
'wait': 1 * 60 + 57
},
{
'text': '',
'wait': 57
}
]
},
{
'video': 'movie 2.mp4',
'questions': [
{
'text': 'How happy are you right now',
'wait': 2
},
{
'text': 'How sad are you right now',
'wait': 5
}
]
}
}
And the real JS code:
// -- base settings
identifier = new Date().getTime();
videos_path = 'videos/';
// -- create elements
var player = videojs('video');
var slider = $('#ex1');
// -- variables
var debug = true;
var timer = null;
var questions = [];
var currquestion = 0;
var currvideo = 0;
function log(msg){
if (debug)
console.log(msg);
}
function checkForLocalStorage(){
var result = false;
try {
result = (typeof window.localStorage == 'undefined');
} catch (err){
result = false;
}
return result;
}
function save(key, value){
log('Saving ' + key + ' -> ' + value);
var sessionObject = localStorage.getItem( identifier );
sessionObject = (null == sessionObject) ? {} : JSON.parse(sessionObject);
sessionObject[key] = value;
localStorage.setItem(identifier, JSON.stringify(sessionObject));
}
function toDate(ms){
var d = new Date(0);
d.setUTCSeconds(ms / 1000);
return d.toLocaleString();
}
function loadAll(){
var result = [];
log('Loading from localstorage:');
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var obj = JSON.parse( localStorage.getItem(key) );
obj['timestamp'] = toDate(key);
log(obj);
result.push( obj );
}
return result;
}
function refreshVideoCount(){
log('Refreshing video counter');
$('#currvideoCounter').text( currvideo +1 );
$('#totalvideoCounter').text( videos.length );
}
function showEnd(){
log('Showing end page');
$('#ending').removeClass('hidden');
$('#videoPlayer').addClass('hidden');
$('#menuEnd').addClass('active');
$('#menuVideos').removeClass('active');
}
function showQuestion(){
console.log('Showing question, currquestion ' + currquestion + ' currvideo ' + currvideo);
clearTimeout(timer);
$('#modalTitle').html( questions[currquestion]['text'] );
$('#modalQuestion').modal('show');
$('#btnModal').on('click', function(){
log('btnModal clicked, saving answer');
save('V' + currvideo + ' Q' + currquestion, slider.slider('getValue'));
log('Refreshing slider');
slider.slider('refresh');
var next = (currquestion >= questions.length-1);
if (next == true){
log('currquestion is the last one, cycling to next video');
currvideo = currvideo +1;
currquestion = 0;
cycleVideos();
} else {
log('cycling to next question of this video');
currquestion = currquestion +1;
cycleQuestions();
}
});
}
function cycleQuestions(){
log('Resuming video');
var questionText = questions[currquestion]['text'];
var questionWait = questions[currquestion]['wait'];
player.play();
if (timer){
log('Clearing timer (cycleQuestions)');
clearTimeout(timer);
timer = null;
}
log('Setting new timer');
timer = setTimeout(function(){
log('Timer triggered, pausing player and showing question');
player.pause();
showQuestion();
}, questionWait * 1000);
}
function cycleVideos(){
log('Cycling to next video');
if (timer){
log('Clearing timer (cycleVideos)');
clearTimeout(timer);
timer = null;
}
if (currvideo > videos.length -1){
log('Video is the last one, showing end page');
player.pause();
player.exitFullscreen();
return showEnd();
}
log('Setting videofile and question variable');
videoFile = videos_path + videos[currvideo]['video'];
questions = videos[currvideo]['questions'];
refreshVideoCount();
log('Playing player');
player.src({ 'src' : videoFile });
player.play();
cycleQuestions();
}
function showOverview(){
log('Showing management page');
$('#intro').addClass('hidden');
$('#overview').removeClass('hidden');
var items = loadAll();
var content = '';
log('Generating table');
var table =
$('<table>')
.addClass('table')
.append('<thead><tr>');
for (var prop in items[0])
table.append('<th>' + prop + '</th>');
table
.append('</tr></thead>')
.append('<tbody>');
items.forEach(function(object){
// for every entry
var row = '<tr>';
for (var property in items[0]) {
if (object.hasOwnProperty(property)) {
// for every property
row = row.concat(
'<td>' + object[property] + '</td>'
);
}
}
row.concat('</tr>');
table.append(row);
});
table.append('</table>');
$('#overviewText').html(table);
$('#btnClear').on('click', function(){
log('Clearing storage');
if ( confirm('Do you really want to clear all results?') ){
localStorage.clear();
location.reload();
}
});
}
function showIntro(){
log('Showing intro page');
$('#menuIntro').addClass('active');
refreshVideoCount();
$('#intro').removeClass('hidden');
$('#introInput').keyup(function(event){
if(event.keyCode == 13)
$("#introBtn").click();
});
$('#introBtn').on('click', function(){
var name = $('#introInput').val();
var age = $('#introAge').val();
var gender = $('#introGender').val();
if (name.trim().length == 0)
return alert('You need to fill in your name.');
if (age.trim().length == 0)
return alert('You need to fill in your age.');
if (name === settings['masterpassword'])
return showOverview();
save('name', name);
save('age', age);
save('gender', gender);
$('#intro').addClass('hidden');
$('#videoPlayer').removeClass('hidden');
$('#menuIntro').removeClass('active');
$('#menuVideos').addClass('active');
slider.slider({});
player.requestFullscreen();
cycleVideos();
});
}
function disableRefresh(){
log('Disabling F5');
$(document).on("keydown", function(e){
if ((e.which || e.keyCode) == 116)
e.preventDefault();
});
}
// setup base stuff
checkForLocalStorage();
$('#logo').text( settings['appname'] );
$('#title').text( settings['appname'] );
disableRefresh();
// show intro page
showIntro( identifier );
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.
Is there any plugin similar to the iPad-like password field behaviour. We need to show only the focus number that the customer enters when they enter their credit card number, and then switch to a bullet once the customer types the next number.
For numbers that have been entered prior to the number being entered, they all need to be changed to the bullet style.
Not sure about Jquery plugin. tried this out. Hope this works for you - http://jsfiddle.net/Lhw7xcy6/12/
(function () {
var config = {},
bulletsInProgress = false,
bulletTimeout = null,
defaultOpts = {
className: 'input-long',
maxLength: '16',
type: 'tel',
autoComplete: 'off'
};
var generateBullets = function (n) {
var bullets = '';
for (var i = 0; i < n; i++) {
bullets += "\u25CF";
}
return bullets;
},
getCursorPosition = function (elem) {
var el = $(elem).get(0);
var pos = 0;
var posEnd = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
posEnd = Sel.text.length;
}
return [pos, posEnd];
},
keyInputHandler = function (e, elem, $inpField) {
var keyCode = e.which || e.keyCode,
timeOut = 0,
$bulletField = $(elem),
tempInp = $bulletField.data('tempInp'),
numBullets = $bulletField.data('numBullets');
var position = getCursorPosition(elem);
if (keyCode >= 48 && keyCode <= 57) {
e.preventDefault();
clearTimeout(bulletTimeout);
$bulletField.val(generateBullets(numBullets) + String.fromCharCode(keyCode));
tempInp += String.fromCharCode(keyCode);
numBullets += 1;
bulletsInProgress = true;
timeOut = 3000;
} else if (keyCode == 8) {
clearTimeout(bulletTimeout);
tempInp = (position[0] == position[1]) ? tempInp.substring(0, position[0] - 1) + tempInp.substring(position[1]) : tempInp.substring(0, position[0]) + tempInp.substring(position[1]);
numBullets = (position[0] == position[1]) ? numBullets - 1 : numBullets - (position[1] - position[0]);
tempInp = ($.trim($bulletField.val()) === '') ? '' : tempInp;
numBullets = ($.trim($bulletField.val()) === '') ? 0 : numBullets;
timeOut = 0;
} else {
e.preventDefault();
return false;
}
$bulletField.data('numBullets', numBullets);
$bulletField.data('tempInp', tempInp);
$inpField.val(tempInp);
$('#output').val(tempInp); // testing purpose
bulletTimeout = setTimeout(function () {
$bulletField.val(generateBullets(numBullets));
bulletsInProgress = false;
}, timeOut);
};
$.fn.bulletField = function (options) {
var opts = $.extend({}, defaultOpts, options);
//console.log(opts);
this.each(function () {
var $inpField = $(this),
id = $inpField.attr('id');
$inpField.after('<input id="bullet_' + id + '" type=' + opts.type + ' maxlength=' + opts.maxLength + ' autocomplete=' + opts.autoComplete + ' class=' + opts.className + '>');
$inpField.hide();
var bulletFieldId = 'bullet_' + id;
var $bulletField = $('#' + bulletFieldId);
$bulletField.data('numBullets', 0);
$bulletField.data('tempInp', '');
$('#' + bulletFieldId).on('keydown', function (e) {
keyInputHandler(e, this, $inpField);
});
$('#' + bulletFieldId).on('blur', function () {
//$inpField.trigger('blur');
});
});
return this;
};
}());
$(function () {
/*USAGE - invoke the plugin appropriately whenever needed. example -onclick,onfocus,mousedown etc.*/
//$('body').on('mousedown', '#bulletField', function () {
$('#bulletField').bulletField();
//$('body').off('mousedown');
// });
/* ---OR ----
$('#bulletField').bulletField({
className: 'input-short',
maxLength : '4'
});*/
});