How to load first video in playlist using javascript - javascript

I am using the tubeplayer plugin to generate video playlists for my hot 100 music chart website http://beta.billboard.fm.
I pull playlist data and generate video playlists based on that data. The problem is that I currently am manually entering the youtube video ID for initial video load video on the home page, where I would like to create a variable that dynamically pulls the first youtube video id and inserts after initialVideo
So I am trying to create a variable that pulls track #1 from the hot 100 year playlist that I can place in the standard plugin parameters:
I will define it as var initialVideoID =
<script>
// IE workaround
function JSONQuery(url, callback) {
if ($.browser.msie && window.XDomainRequest) {
// alert('ie');
// var url = "http://gdata.youtube.com/feeds/api/videos?q=cher&category=Music&alt=json";
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onerror = function () {
console.log('we have an error!');
}
xdr.onprogress = function () {
// console.log('this sucks!');
};
xdr.ontimeout = function () {
console.log('it timed out!');
};
xdr.onopen = function () {
console.log('we open the xdomainrequest');
};
xdr.onload = function () {
// XDomainRequest doesn't provide responseXml, so if you need it:
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = true;
dom.loadXML(xdr.responseText);
// alert(xdr.responseText);
callback(jQuery.parseJSON(xdr.responseText));
// alert(data.feed.entry[0].media$group.media$content[0].url);
// alert("ie");
};
xdr.send();
} else {
$.getJSON(url, callback);
}
};
var yearMap = [];
createYearMap();
function createYearMap() {
yearMap["1940"] = [1946, 1947, 1948, 1949];
yearMap["2010"] = [2010, 2011, 2012];
for (var i = 195; i < 201; i++) {
var curDecade = i * 10;
yearMap[curDecade.toString()] = [];
for (var j = 0; j < 10; j++) {
yearMap[curDecade][j] = curDecade + j;
}
}
}
// console.log(yearMap["2010"]);
(function ($) {
$(window).ready(function () {
// alert("before get");
// $.get("test.htm", function(data) {
// // var fileDom = $(data);
// // alert("get callback");
// $("#jqueryTest").html(data);
// });
// setInterval(function(){alert("Hello")},3000);
$(".song-description").mCustomScrollbar();
// var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" +"pink floyd" + "&track=" + "money" + "&format=json";
// JSONQuery(url, function(data) {
// if (data.track) {
// if (data.track.wiki) {
// $("#song-info").html(data.track.wiki.summary);
// } else {
// $("#song-info").html("No song info found");
// }
// } else {
// $("#song-info").html("No song info found");
// console.log("artist not found");
// }
// $(".song-description").mCustomScrollbar("update");
// });
// $("#example tbody tr").click(function() {
// selectPlaying(this, true);
// });
jQuery(".youtube-video").tubeplayer({
width: 300, // the width of the player
height: 225, // the height of the player
allowFullScreen: "true", // true by default, allow user to go full screen
initialVideo: var initialvideoID, // the video that is loaded into the player
preferredQuality: "default", // preferred quality: default, small, medium, large, hd720
showinfo: true, // if you want the player to include details about the video
modestbranding: true, // specify to include/exclude the YouTube watermark
wmode: "opaque", // note: transparent maintains z-index, but disables GPU acceleratio
theme: "dark", // possible options: "dark" or "light"
color: "red", // possible options: "red" or "white"
onPlayerEnded: function () {
videoEnded();
},
onPlayerPlaying: function (id) {
setIconToPause();
}, // after the play method is called
onPlayerPaused: function () {
setIconToPlay();
}, // after the pause method is called
onStop: function () {}, // after the player is stopped
onSeek: function (time) {}, // after the video has been seeked to a defined point
onMute: function () {}, // after the player is muted
onUnMute: function () {} // after the player is unmuted
});
setInterval(function () {
updateProgressBar()
}, 1000);
loadPlaylist("hot100", true);
});
})(jQuery);
var initialvideoID = "yyDUC1LUXSU"
function videoEnded() {
nextVideo();
}
var intervalTimer;
function startPlayer() {
jQuery(".youtube-video").tubeplayer("play");
playing = true;
clearInterval(intervalTimer);
intervalTimer = setInterval(function () {
updateProgressBar()
}, 1000);
setIconToPause();
}
function setIconToPause() {
var button = $(".icon-play");
if (button) {
button.removeClass("icon-play")
button.addClass("icon-pause");
}
}
function setIconToPlay() {
var button = $(".icon-pause");
if (button) {
button.removeClass("icon-pause")
button.addClass("icon-play");
}
}
function pausePlayer() {
jQuery(".youtube-video").tubeplayer("pause");
playing = false;
clearInterval(intervalTimer);
setIconToPlay();
}
function selectPlaying(item, autoStart) {
var nowPlayingItem = $(".nowPlaying");
if (nowPlayingItem) {
nowPlayingItem.removeClass("nowPlaying");
}
$(item).addClass("nowPlaying");
var aPos = $('#example').dataTable().fnGetPosition(item);
var aData = $('#example').dataTable().fnGetData(aPos);
if (aData[3]) {
// $("#song-info").html("Loading song info...");
$("#song-info").html("");
var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" + aData[1] + "&track=" + aData[2] + "&format=json";
JSONQuery(url, function (data) {
if (data.track) {
if (data.track.wiki) {
$("#song-info").html(data.track.wiki.summary);
} else {
$("#song-info").html("No song info found");
}
} else {
$("#song-info").html("No song info found");
console.log("artist not found");
}
// $(".song-description").mCustomScrollbar("update");
});
$(".info-rank").html("#" + aData[0]);
$(".info-artist").html(aData[1]);
$(".info-song").html(aData[2]);
$(".info-year").html($("#navYear").html());
var ytId = aData[3];
if (autoStart) {
jQuery(".youtube-video").tubeplayer("play", ytId);
setIconToPause();
} else {
jQuery(".youtube-video").tubeplayer("cue", ytId);
setIconToPlay();
}
clearInterval(intervalTimer);
intervalTimer = setInterval(function () {
updateProgressBar()
}, 1000);
playing = true;
// alert("youtube video id is: " + ytId);
} else {
alert("no youtube id");
}
}
function previousVideo() {
var curPlaying = $(".nowPlaying")[0];
var nextItem;
if (curPlaying) {
nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, false);
if (!nextItem) {
nextItem = $('#example').dataTable().fnGetNodes($('#example').dataTable().fnSettings().fnRecordsTotal() - 1);
}
} else {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
selectPlaying(nextItem, true);
}
function nextVideo() {
var curPlaying = $(".nowPlaying")[0];
var nextItem;
if (curPlaying) {
nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, true);
if (!nextItem) {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
} else {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
selectPlaying(nextItem, true);
}
function updateProgressBar() {
// console.log("update bar");
myData = jQuery(".youtube-video").tubeplayer("data");
// console.log("update progress bar: " + (myData.currentTime / myData.duration * 100) + "%");
$(".bar").width((myData.currentTime / myData.duration * 100) + "%");
}
var playing = false;
function playPauseClick() {
if (playing) {
pausePlayer();
} else {
startPlayer();
}
}
function loadPlaylist(year) {
loadPlaylist(year, false);
}
function loadPlaylist(year, cueVideo) {
$.get("playlist/" + year + "playlist.txt", function (data) {
// var fileDom = $(data);
// alert("get callback");
// $("#playlistContents").html(data);
// $('#example').dataTable().fnAddData(data);
// var obj = eval("[[1,2,3],[1,2,3]]");
// obj = eval(data.toString());
obj = $.parseJSON(data);
// console.log(obj);
$('#example').dataTable().fnClearTable();
$('#example').dataTable().fnAddData(obj);
// $("#example tbody tr").click(function() {
// selectPlaying(this, true);
// });
if (year == "hot100") {
$("#navYear").html("Weekly Hot 100");
$("#navYearLabel").hide();
} else {
$("#navYear").html(year);
$("#navYearLabel").show();
}
if (cueVideo) {
selectPlaying($('#example').dataTable().fnGetNodes(0), false);
}
// $('#example').dataTable().fnAddData(data);
});
}
function modalDecadeClick(decade) {
var string = "";
if (decade == 'hot100') {
loadPlaylist("hot100");
$('#modal-example-decade').modal('hide');
$('#modal-year').modal('hide');
} else {
for (var i = 0; i < yearMap[decade].length; i++) {
string += '<li>' + yearMap[decade][i] + '</li>';
}
$('#modal-example-decade').modal('hide');
$('#specific-year-list').empty();
$('#specific-year-list').html(string).contents();
}
}
function modalYearClick(node) {
var year = parseInt($(node).children("li").html());
// console.log($(node).children("li").html());
$('#modal-year').modal('hide');
loadPlaylist(year);
}
function progressBarClick(e) {
var seekPercent = (e.pageX - $(".progress:first").offset().left) / $(".progress:first").width();
var seekTime = jQuery(".youtube-video").tubeplayer("data").duration * seekPercent;
jQuery(".youtube-video").tubeplayer("seek", seekTime);
}
var minYear = 1946;
var maxYear = 2012;
function nextYear() {
var year = $("#navYear").html();
if (year == "Weekly Hot 100") {
alert("Max year is " + maxYear);
return;
}
year = parseInt($("#navYear").html());
year++;
if (year > maxYear) {
loadPlaylist("hot100");
return;
}
loadPlaylist(year);
}
function prevYear() {
var year = $("#navYear").html();
if (year == "Weekly Hot 100") {
loadPlaylist(2012);
return;
}
year = parseInt($("#navYear").html());
year--;
if (year < minYear) {
alert("Min year is " + minYear);
return;
}
loadPlaylist(year);
}
function closeFilter() {
toggle_visibility('toggle-filter');
var oTable = $('#example').dataTable();
// Sometime later - filter...
oTable.fnFilter('');
}
</script>

Related

WebRTC video stream works on some devices but does not work on other devices

I've been working on an app that uses webRTC and it works perfectly on all of MY devices from different networks. However, when other people try to use it from their devices, some can connect and some can't. I collected all the WebRTC chrome internal dumps and attached some of them below.
Local dump link:
https://www.dropbox.com/home?preview=local_dump.txt
Working device(remote) dump link:
https://www.dropbox.com/home?preview=working_device_dump.txt
Not working device(remote) dump link:
https://www.dropbox.com/home?preview=not_working_dump.txt
Javascript is attached below:
I traversed a number of stackoverflow posts and my JS should be up-to-date. I am guessing the codecs are making the stream fail but I don't know what to fix.
// get DOM elements
var dataChannelLog = document.getElementById('data-channel'),
iceConnectionLog = document.getElementById('ice-connection-state'),
iceGatheringLog = document.getElementById('ice-gathering-state'),
signalingLog = document.getElementById('signaling-state');
// peer connection
var pc = null;
// data channel
var dc = null, dcInterval = null;
function createPeerConnection() {
var config = {
sdpSemantics: 'unified-plan'
};
if (document.getElementById('use-stun').checked) {
config.iceServers = [{urls: ['stun:stun.l.google.com:19302']}];
}
var pc = new RTCPeerConnection(config);
// connect audio / video
pc.addEventListener('track', function(evt) {
if (evt.track.kind == 'video')
document.getElementById('video').srcObject = evt.streams[0];
else
document.getElementById('audio').srcObject = evt.streams[0];
});
return pc;
}
function negotiate() {
return pc.createOffer().then(function(offer) {
return pc.setLocalDescription(offer);
}).then(function() {
// wait for ICE gathering to complete
return new Promise(function(resolve) {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange', checkState);
resolve();
}
}
pc.addEventListener('icegatheringstatechange', checkState);
}
});
}).then(function() {
var offer = pc.localDescription;
var codec;
codec = document.getElementById('audio-codec').value;
// if (codec !== 'default') {
// offer.sdp = sdpFilterCodec('audio', codec, offer.sdp);
// }
//
// codec = document.getElementById('video-codec').value;
// if (codec !== 'default') {
// offer.sdp = sdpFilterCodec('video', codec, offer.sdp);
// }
document.getElementById('offer-sdp').textContent = offer.sdp;
console.log(offer);
return fetch('/offer', {
body: JSON.stringify({
sdp: offer.sdp,
type: offer.type,
video_transform: document.getElementById('video-transform').value
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
}).then(function(response) {
return response.json();
}).then(function(answer) {
document.getElementById('answer-sdp').textContent = answer.sdp;
return pc.setRemoteDescription(answer);
}).catch(function(e) {
/*
TODO: Presentation and logic mix a lot here (naturally). I don't think we need a framework (even though the
JS world has ALL OF THEM), but maybe we can group all presentation related things in separate functions,
for example change this to be catch(showConnectionError) and put the DOM logic inside
function showConnectionError(e) {...}?
*/
var el = document.querySelector('video');
var newEl = document.createElement('img');
newEl.src = '/working.png';
newEl.style.height = '100%'
el.parentNode.replaceChild(newEl, el);
});
}
function start() {
document.getElementById('start').style.display = 'none';
pc = createPeerConnection();
var time_start = null;
function current_stamp() {
if (time_start === null) {
time_start = new Date().getTime();
return 0;
} else {
return new Date().getTime() - time_start;
}
}
if (document.getElementById('use-datachannel').checked) {
var parameters = JSON.parse(document.getElementById('datachannel-parameters').value);
dc = pc.createDataChannel('chat', parameters);
dc.onclose = function() {
clearInterval(dcInterval);
dataChannelLog.textContent += '- close\n';
};
dc.onopen = function() {
dataChannelLog.textContent += '- open\n';
dcInterval = setInterval(function() {
var message = 'ping ' + current_stamp();
dataChannelLog.textContent += '> ' + message + '\n';
dc.send(message);
}, 1000);
};
dc.onmessage = function(evt) {
dataChannelLog.textContent += '< ' + evt.data + '\n';
if (evt.data.substring(0, 4) === 'pong') {
var elapsed_ms = current_stamp() - parseInt(evt.data.substring(5), 10);
dataChannelLog.textContent += ' RTT ' + elapsed_ms + ' ms\n';
}
};
}
var constraints = {
audio: document.getElementById('use-audio').checked,
video: false
};
if (document.getElementById('use-video').checked) {
var resolution = document.getElementById('video-resolution').value;
if (resolution) {
resolution = resolution.split('x');
constraints.video = {
width: parseInt(resolution[0], 0),
height: parseInt(resolution[1], 0)
};
} else {
constraints.video = true;
}
}
if (constraints.audio || constraints.video) {
if (constraints.video) {
document.getElementById('media').style.display = 'block';
}
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
stream.getTracks().forEach(function(track) {
pc.addTrack(track, stream);
});
return negotiate();
/*
TODO: Can this also be promise-based? -> .catch(function(err) { ... })
*/
}, function(err) {
alert('Could not acquire media: ' + err);
});
} else {
negotiate();
}
document.getElementById('stop').style.display = 'inline-block';
}
function stop() {
document.getElementById('stop').style.display = 'none';
// close data channel
if (dc) {
dc.close();
}
// close transceivers
if (pc.getTransceivers) {
pc.getTransceivers().forEach(function(transceiver) {
if (transceiver.stop) {
transceiver.stop();
}
});
}
// close local audio / video
pc.getSenders().forEach(function(sender) {
sender.track.stop();
});
// close peer connection
setTimeout(function() {
pc.close();
}, 500);
}
function sdpFilterCodec(kind, codec, realSdp) {
var allowed = []
var rtxRegex = new RegExp('a=fmtp:(\\d+) apt=(\\d+)\r$');
var codecRegex = new RegExp('a=rtpmap:([0-9]+) ' + escapeRegExp(codec))
var videoRegex = new RegExp('(m=' + kind + ' .*?)( ([0-9]+))*\\s*$')
var lines = realSdp.split('\n');
var isKind = false;
for (var i = 0; i < lines.length; i++) {
if (lines[i].startsWith('m=' + kind + ' ')) {
isKind = true;
} else if (lines[i].startsWith('m=')) {
isKind = false;
}
if (isKind) {
var match = lines[i].match(codecRegex);
if (match) {
allowed.push(parseInt(match[1]));
}
match = lines[i].match(rtxRegex);
if (match && allowed.includes(parseInt(match[2]))) {
allowed.push(parseInt(match[1]));
}
}
}
var skipRegex = 'a=(fmtp|rtcp-fb|rtpmap):([0-9]+)';
var sdp = '';
isKind = false;
for (var i = 0; i < lines.length; i++) {
if (lines[i].startsWith('m=' + kind + ' ')) {
isKind = true;
} else if (lines[i].startsWith('m=')) {
isKind = false;
}
if (isKind) {
var skipMatch = lines[i].match(skipRegex);
if (skipMatch && !allowed.includes(parseInt(skipMatch[2]))) {
continue;
} else if (lines[i].match(videoRegex)) {
sdp += lines[i].replace(videoRegex, '$1 ' + allowed.join(' ')) + '\n';
} else {
sdp += lines[i] + '\n';
}
} else {
sdp += lines[i] + '\n';
}
}
return sdp;
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

i have a tempermonkey script which read data from csv file .....i want to change it based on fields on webpage

The script loads data from a CSV file. Page sometimes has five fields,
sometimes four. The script needs to adjust based on the number of fields.
forexample I need to modify this tempermonkey script
enter 4 pieces of data if there are 4 fields or enter 5 pieces of data if
there are 5 fields on the web page.
$(window).ready(function($) {
var file = GM_getResourceText('csvFile');
var csv = $.csv.toArrays(file);
var row = 0;
//var interval = setInterval(fillFormInterval, 3000);
var scope = angular.element($('body')).scope();
// scope.$on('$includeContentLoaded', function(){
// fillForm(csv[row]);
//setTimeout(fillForm(csv[row]));
//});
var interval = setInterval(fillFormInterval, 1000);
functionfillFormInterval() {
if($('#applicant-preferredCommunicationMethod').length) {
clearInterval(interval);
setTimeout(function() {
fillForm(csv[row]);
},3000);
}
}
functionfillForm(tempRow) {
var scope = angular.element($('#applicant-firstName')).scope();
if(!scope.applicant || !scope.applicant.phone1) {
return;
}
var row = new Array(5).fill(undefined);
row[1] = "NMN";
tempRow.forEach(function(data,i) {
if(data != '') {
row[i] = data;
}
});
scope.$apply(function() {
scope.applicant.firstName = row[0];
scope.applicant.middleName = row[1];
scope.applicant.lastName = row[2];
scope.applicant.dateOfBirth = row[3];
scope.applicant.dateOfBirth2 = row[3];
scope.applicant.phone1.number = row[4];
scope.applicant.preferredCommunicationMethod = "PHONE1";
scope.inherited.next();
});
//scope.applicant.countryOfBirth = "CD";
}
var interval_2 = setInterval(fillFormInterval_2, 1000);
function fillFormInterval_2() {
if($('#applicant-countryOfBirth').length) {
clearInterval(interval_2);
setTimeout(function() {
fillForm_2(csv[row]);
},3000);
}
}
functiondropDownVal(id, text) {
var value = null;
$(id).each(function() {
if(this.text.toLowerCase() == text) {
value = this.value;
value = value.split(':');
if(value.length> 1) {
value = value[1];
}else {
value = value[0];
}
}
});
return value;
}
function fillForm_2(data) {
var scope = angular.element($('#applicant-
countryOfBirth')).scope();
var country = '';
country = dropDownVal('#applicant-countryOfBirth option',
data[5].toLowerCase());
//scope.applicant.countryOfBirth = country;
var state = null;
scope.$apply(function() {
scope.applicant.countryOfBirth = country;
scope.updateStateProvince(scope.applicant.countryOfBirth);
setTimeout(function() {
if(country == "US" || country == "CD" || country == "MM") {
state = dropDownVal('#applicant-stateProvinceOfBirth
option', data[6].toLowerCase());
}
var citizen = dropDownVal('#applicant-countryOfCitizenship
option', data[7].toLowerCase());
console.log(country + " " + state + " " + citizen);
scope.applicant.countryOfCitizenship = citizen;
scope.applicant.stateProvinceOfBirth = state;
scope.$apply();
scope.inherited.next();
});
});
}
var interval_3 = setInterval(fillFormInterval_3, 1000);
function fillFormInterval_3() {
if($('.personal-questions').length) {
clearInterval(interval_3);
setTimeout(function() {
fillForm_3(csv[row]);
},3000);
}
}
function fillForm_3(data) {
e.applicant.hasMaidenPreviousName = false;
scope.applicant.hasAliasName = false;
scope.applicant.hasSameMailingResidentialAddress = true;
scope.applicant.doYouHaveAuthCode = false;
scope.applicant.viewEcNearYou = false;
scope.inherited.next();
});
}
var interval_4 = setInterval(fillFormInterval_4, 1000);
function fillFormInterval_4() {
if($('#ue-btn-US').length) {
clearInterval(interval_4);
setTimeout(function() {
fillForm_4(csv[row]);
},3000);
}
}
function fillForm_4(data) {
var scope = angular.element($('#applicant-eyeColor')).scope();
scope.$apply(function() {
scope.heightFt = parseInt(data[8].substr(0,1));
scope.heightIn = parseInt(data[8].substr(1,3));
scope.weightLb = parseInt(data[9]);
scope.applicant.hairColor = dropDownVal('#applicant-hairColor
option',
data[10].toLowerCase());
scope.applicant.eyeColor = dropDownVal('#applicant-eyeColor
option',
data[11].toLowerCase());
scope.applicant.gender = dropDownVal('#applicant-gender
option',
data[12].toLowerCase());
if(data[13].toLowerCase() == 'mixed race') {
data[13] = 'Unknown';
}else if(data[13].toLowerCase() == 'white' ||
data[13].toLowerCase() ==
'hispanic') {
data[13] = 'Caucasian/Latino';
}
scope.applicant.race = dropDownVal('#applicant-race option',
data[13].toLowerCase());
scope.inherited.next();
});
}
var interval_5 = setInterval(fillFormInterval_5, 1000);
function fillFormInterval_5() {
if($('#applicant-mailingAddress-country').length) {
clearInterval(interval_5);
setTimeout(function() {
fillForm_5(csv[row]);
},3000);
}
}
function fillForm_5(data) {
var scope = angular.element($('#applicant-mailingAddress-
country')).scope();
scope.$apply(function() {
scope.applicant.mailingAddress = {};
scope.applicant.mailingAddress.country = "US";
scope.updateStates('mailingAddress');
scope.applicant.mailingAddress.addressLine1 = data[14];
scope.applicant.mailingAddress.addressLine2 = data[15];
scope.applicant.mailingAddress.city = data[16];
setTimeout(function() {
scope.$apply(function() {
scope.applicant.mailingAddress.state = dropDownVal('#applicant-
mailingAddress-state option', data[17].toLowerCase());
scope.applicant.mailingAddress.postalCode = data[18];
scope.inherited.next();
});
});
//scope.inherited.next();
});
}
var interval_6 = setInterval(fillFormInterval_6, 1000);
function fillFormInterval_6() {
if($('#designatedRecipient-name').length) {
clearInterval(interval_6);
setTimeout(function() {
fillForm_6(csv[row]);
},3000);
}
}
function fillForm_6(data) {
var scope = angular.element($('#designatedRecipient-
name')).scope();
scope.$apply(function() {
scope.applicant.designatedRecipientName = "BIOVERIFY INC";
scope.applicant.designatedRecipientAddress = {};
scope.applicant.designatedRecipientAddress.country = "US";
scope.applicant.designatedRecipientAddress.addressLine1 = "2535
Manana
Dr.";
scope.applicant.designatedRecipientAddress.city = "Dallas";
setTimeout(function() {
scope.$apply(function() {
scope.applicant.designatedRecipientAddress.state =
dropDownVal('#applicant-designatedRecipientAddress-state
option', 'texas');
scope.applicant.designatedRecipientAddress.postalCode =
"75220";
scope.inherited.next();
});
});
scope.updateStates();
});
}
var interval_7 = setInterval(fillFormInterval_7, 1000);
function fillFormInterval_7() {
if($('#payment-nameOnCard').length) {
clearInterval(interval_7);
setTimeout(function() {
fillForm_7(csv[row]);
},3000);
}
}
function fillForm_7(data) {
var scope = angular.element($('#payment-nameOnCard')).scope();
scope.$apply(function() {
scope.applicant.payment.nameOnCard = "Brendan J Berrells";
scope.applicant.payment.cardNumber = "4246315197117185";
scope.applicant.payment.expiration = {};
scope.applicant.payment.expiration.month = 11;
scope.applicant.payment.expiration.year = "19";
scope.applicant.payment.csc = "255";
});
}
});

TypeError: Cannot create property 'style' on string 'a'

Honestly do not know whats happen, this was working this morning, have not changed a thing but now when i click my button to generate my images I get this error.
Can anyone tell me why and how to fix this please.
Error
test initMock test generate 1
TypeError: Cannot create property 'style' on string 'a'
at i._createCanvasElement (fabric.min.js:2)
at i._createLowerCanvas (fabric.min.js:2)
at i._initStatic (fabric.min.js:2)
at initialize (fabric.min.js:3)
at new i (fabric.min.js:1)
at b.$scope.uploadImage (controller.js:855)
at b.$scope.generate (controller.js:929)
at fn (eval at compile (angular.js:15500), <anonymous>:4:144)
at e (angular.js:27285)
at b.$eval (angular.js:18372)
my functions
$scope.uploadImage = function (where) {
var deferred = $q.defer();
if (where === 'upload') {
var f = document.getElementById('uploadCreative').files[0];
var r = new FileReader();
r.onload = function () {
var image = new Image();
image.src = r.result;
image.onload = function () {
$scope.resize(image.src).then(function (response) {
deferred.resolve(response);
console.log('hehe NO!');
console.log('hehe NO!');
}).catch(function (response) {
})
}
};
r.readAsDataURL(f);
}
if (where === 'local') {
function ax(a, callback) {
callback(localStorage.getItem(a));
}
var loadCanvas = new fabric.Canvas('a');
divHeight = $('.image-builder').height();
if ($scope.format === '1') {
Aratio = 0.67;
} else if ($scope.format === '2') {
Aratio = 0.56;
} else if ($scope.format === '3') {
divHeight = divHeight / 1.5;
Aratio = 2;
} else if ($scope.format === '4') {
Aratio = 0.67;
} else {
Aratio = 1
}
loadCanvas.setHeight(divHeight - 15);
loadCanvas.setWidth((divHeight - 15) * Aratio);
if (localStorage.getItem('backgroundImage') !== 'null') {
background = localStorage.getItem('backgroundImage');
var imgBc = new Image();
imgBc.onload = function () {
// this is syncronous
Iwidth = this.width;
Iheight = this.height;
var f_img = new fabric.Image(imgBc);
loadCanvas.setBackgroundImage(f_img, loadCanvas.renderAll.bind(loadCanvas), {
scaleY: loadCanvas.height / Iheight,
scaleX: loadCanvas.width / Iwidth
});
var test = ax('CC-canvas', function (response) {
loadCanvas.loadFromJSON(response, function () {
loadCanvas.renderAll();
$scope.resize(loadCanvas.toDataURL()).then(function (response) {
deferred.resolve(response);
}).catch(function (response) {
})
});
});
};
imgBc.src = background;
} else {
var test = ax('CC-canvas', function (response) {
loadCanvas.loadFromJSON(response, function () {
loadCanvas.renderAll();
$scope.resize(loadCanvas.toDataURL()).then(function (response) {
deferred.resolve(response);
}).catch(function (response) {
console.log(response);
})
});
});
}
}
return deferred.promise;
};
$scope.generate = function () {
$scope.generating = true;
$scope.generateBtn = 'Generating';
for (i = 0; i < $scope.gallery.length; i++) {
$scope.select[i] = '';
}
$scope.gallery = [];
$scope.checkPhoto = [];
console.log("test generate 1");
$scope.uploadImage($scope.creative).then(function (result) {
console.log("test generate 2");
$scope.generateCanvas(result, $scope.left, $scope.tops, $scope.wi, $scope.hi, $scope.per, $scope.btmR, $scope.btmL, $scope.backUrl)
.then(function () {
$timeout(function () {
//push final photo to array befor send to back end
$scope.photosToPhp.push(canvas2.toDataURL());
}, 800);
if ($scope.count < ($scope.photos[$scope.format].length - 1)) {
$scope.generate();
$scope.count++;
$scope.left = $scope.photos[$scope.format][$scope.count]['left'];
$scope.tops = $scope.photos[$scope.format][$scope.count]['tops'];
$scope.wi = $scope.photos[$scope.format][$scope.count]['wi'];
$scope.hi = $scope.photos[$scope.format][$scope.count]['hi'];
$scope.per = $scope.photos[$scope.format][$scope.count]['per'];
$scope.btmR = $scope.photos[$scope.format][$scope.count]['btmR'];
$scope.btmL = $scope.photos[$scope.format][$scope.count]['btmL'];
$scope.backUrl = "/mm3/public/img/formats/" + $scope.format + "/" + $scope.photos[$scope.format][$scope.count]['backUrl'];
$scope.$apply();
console.log("test generate 3");
} else {
//all photos've been pushed now sending it to back end
$timeout(function () {
// console.log($scope.photosToPhp[0]);
$http.post('/mm3/savePhoto', $scope.photosToPhp).then(function (success) {
$scope.generating = false;
$scope.generateBtn = 'Generate';
//creating mock up gallery
for (var x = 0; x < success.data.photos; x++) {
var file = '/mm3/tmp/' + success.data.folder + "/out" + x + ".png";
$scope.gallery.push(file);
}
$scope.photosToPhp = [];
}, function (error) {
});
}, 800);
$scope.count = 0;
$scope.left = $scope.photos[$scope.format][$scope.count]['left'];
$scope.tops = $scope.photos[$scope.format][$scope.count]['tops'];
$scope.wi = $scope.photos[$scope.format][$scope.count]['wi'];
$scope.hi = $scope.photos[$scope.format][$scope.count]['hi'];
$scope.per = $scope.photos[$scope.format][$scope.count]['per'];
$scope.btmR = $scope.photos[$scope.format][$scope.count]['btmR'];
$scope.btmL = $scope.photos[$scope.format][$scope.count]['btmL'];
$scope.backUrl = "/mm3/public/img/formats/" + $scope.format + "/" + $scope.photos[$scope.format][$scope.count]['backUrl'];
$scope.$apply();
}
console.log("test generate 4");
})
.catch(function (errorUrl) {
console.log(errorUrl);
})
})
};
Solved bu downgrading fabric js to 1.5 not 1.7 that i upgraded to, dont know why this worked but it dose

I want to add a loading png in LiveSearch

I am using a plugin for live search .. everything is working fine .. i just want to add a loading png that appear on start of ajax request and disappear on results ..
please help me to customize the code just to add class where form id="search-kb-form" .. and remove the class when results are completed.
<form id="search-kb-form" class="search-kb-form" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="wrapper-kb-fields">
<input type="text" id="s" name="s" placeholder="Search what you’re looking for" title="* Please enter a search term!">
<input type="submit" class="submit-button-kb" value="">
</div>
<div id="search-error-container"></div>
</form>
This is the plugin code
jQuery.fn.liveSearch = function (conf) {
var config = jQuery.extend({
url: {'jquery-live-search-result': 'search-results.php?q='},
id: 'jquery-live-search',
duration: 400,
typeDelay: 200,
loadingClass: 'loading',
onSlideUp: function () {},
uptadePosition: false,
minLength: 0,
width: null
}, conf);
if (typeof(config.url) == "string") {
config.url = { 'jquery-live-search-result': config.url }
} else if (typeof(config.url) == "object") {
if (typeof(config.url.length) == "number") {
var urls = {}
for (var i = 0; i < config.url.length; i++) {
urls['jquery-live-search-result-' + i] = config.url[i];
}
config.url = urls;
}
}
var searchStatus = {};
var liveSearch = jQuery('#' + config.id);
var loadingRequestCounter = 0;
// Create live-search if it doesn't exist
if (!liveSearch.length) {
liveSearch = jQuery('<div id="' + config.id + '"></div>')
.appendTo(document.body)
.hide()
.slideUp(0);
for (key in config.url) {
liveSearch.append('<div id="' + key + '"></div>');
searchStatus[key] = false;
}
// Close live-search when clicking outside it
jQuery(document.body).click(function(event) {
var clicked = jQuery(event.target);
if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
});
}
});
}
return this.each(function () {
var input = jQuery(this).attr('autocomplete', 'off');
var liveSearchPaddingBorderHoriz = parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);
// Re calculates live search's position
var repositionLiveSearch = function () {
var tmpOffset = input.offset();
var tmpWidth = input.outerWidth();
if (config.width != null) {
tmpWidth = config.width;
}
var inputDim = {
left: tmpOffset.left,
top: tmpOffset.top,
width: tmpWidth,
height: input.outerHeight()
};
inputDim.topPos = inputDim.top + inputDim.height;
inputDim.totalWidth = inputDim.width - liveSearchPaddingBorderHoriz;
liveSearch.css({
position: 'absolute',
left: inputDim.left + 'px',
top: inputDim.topPos + 'px',
width: inputDim.totalWidth + 'px'
});
};
var showOrHideLiveSearch = function () {
if (loadingRequestCounter == 0) {
showStatus = false;
for (key in config.url) {
if( searchStatus[key] == true ) {
showStatus = true;
break;
}
}
if (showStatus == true) {
for (key in config.url) {
if( searchStatus[key] == false ) {
liveSearch.find('#' + key).html('');
}
}
showLiveSearch();
} else {
hideLiveSearch();
}
}
};
// Shows live-search for this input
var showLiveSearch = function () {
// Always reposition the live-search every time it is shown
// in case user has resized browser-window or zoomed in or whatever
repositionLiveSearch();
// We need to bind a resize-event every time live search is shown
// so it resizes based on the correct input element
jQuery(window).unbind('resize', repositionLiveSearch);
jQuery(window).bind('resize', repositionLiveSearch);
liveSearch.slideDown(config.duration)
};
// Hides live-search for this input
var hideLiveSearch = function () {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
for (key in config.url) {
liveSearch.find('#' + key).html('');
}
});
};
input
// On focus, if the live-search is empty, perform an new search
// If not, just slide it down. Only do this if there's something in the input
.focus(function () {
if (this.value.length > config.minLength ) {
showOrHideLiveSearch();
}
})
// Auto update live-search onkeyup
.keyup(function () {
// Don't update live-search if it's got the same value as last time
if (this.value != this.lastValue) {
input.addClass(config.loadingClass);
var q = this.value;
// Stop previous ajax-request
if (this.timer) {
clearTimeout(this.timer);
}
if( q.length > config.minLength ) {
// Start a new ajax-request in X ms
this.timer = setTimeout(function () {
for (url_key in config.url) {
loadingRequestCounter += 1;
jQuery.ajax({
key: url_key,
url: config.url[url_key] + q,
success: function(data){
if (data.length) {
searchStatus[this.key] = true;
liveSearch.find("#" + this.key).html(data);
} else {
searchStatus[this.key] = false;
}
loadingRequestCounter -= 1;
showOrHideLiveSearch();
}
});
}
}, config.typeDelay);
}
else {
for (url_key in config.url) {
searchStatus[url_key] = false;
}
hideLiveSearch();
}
this.lastValue = this.value;
}
});
});
};
add a background to the loading class
.loading {
background:url('http://path_to_your_picture');
}

JQuery: How to refactor JQuery interaction with interface?

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

Categories

Resources