Enlarge a picture after clicking on it - javascript

I need to enlarge a picture when I click on it.
The problem is that I get this image in my javascript from my database and I don't know how I can do it to change the size of my picture after the click
Here is the js function that use data to create the picture
function loadSynthese(data) {
$.ajax({
cache: false,
url: "data/loadSynthese",
type: "POST",
async: true,
data: ({
dateid: data,
}),
success: function (response, status) {
response.forEach(element => {
css = "";
idonglet = element["id_onglet"];
idprio = element["id_prio"];
texte = element["texte"];
image = element["image_aide"];
if(image === '' || image === null || image === undefined){
htmlPrio = '<div class="intPrio"><p class="titreP">Priorité ' + k + '' + pilote + '</p><img id="' + idonglet + 'imgCheck' + idprio + '" onclick="selectPrioSynth(' + idonglet + ', ' + idprio + ', this)" ' + css + ' alt="Sélectionner la priorité" data-idprio="' + idprio + '"></div><label class="textPrioSynth" onclick="selectPrioSynth(' + idonglet + ', ' + idprio + ', this)" data-idprio="' + idprio + '">' + texte + '</label>';
} else {
img = '</br><img id="image'+ idprio + '" class="imageP" src="data:image/jpeg;base64,' + btoa(image) +'">';
htmlPrio = '<div class="intPrio"><p class="titreP">Priorité ' + k + '' + pilote + '</p><img id="' + idonglet + 'imgCheck' + idprio + '" onclick="selectPrioSynth(' + idonglet + ', ' + idprio + ', this)" ' + css + ' alt="Sélectionner la priorité" data-idprio="' + idprio + '"></div><label class="textPrioSynth" onclick="selectPrioSynth(' + idonglet + ', ' + idprio + ', this)" data-idprio="' + idprio + '">' + texte + '<p class="imageP" onclick="enlargeImg()">' +img+'</p></label>';
}
$("#" + idonglet + "ps").append(htmlPrio);
((nextid == idonglet) ? k++ : k = 1);
j++; i++;
((j < response.length - 1) ? nextid = response[i]['id_onglet'] : "");
});
}
},
error: function (response, status) {
}
});}
And here he function i want to add to change the size of the picture
function enlargeImg(img) {
img.style.width = "60%";
img.style.height = "auto";
img.style.transition = "width 0.5s ease";}
And When i click on the picture I have this issue :
"Uncaught TypeError: Cannot read properties of undefined (reading 'style')"

You can add or remove a css class some-name which has transform:scale(1.5) whereas your img has transition: 0.5s
img {
transition: 0.5s;
}
img:hover,
.some-class {
transform: scale(1.5)
}
<img src="https://picsum.photos/200" style="margin:40px">

Related

Getting Tippy Nested ToolTip Displayed

I've been trying to get Tippy.js' nested tooltip feature working but haven't had luck so far.
the following lines are placed outside jQuery's Document ready function:
tippy.setDefaultProps({
appendTo: function () {
return document.querySelector('.responseBody')
}
})
popperOptions: { strategy: 'fixed' };
tippy.delegate('.responseBody', {
target: '.tooltip'
});
the tooltip content is being added dynamically based on an extract from ajax response and the ajax function is the following:
function _loadLaunchPad(iSMHost, iSMPort, urlExtension) {
var _serverName = $('#serverName option:selected').text();
var _addOnSelect = $('#addOnSelect option:selected').text();
var _consoleCmdExprValue = $('#consoleCmdExprValue').val();
var dataString = '{ "serverSelection" : "' + _serverName + '", "operationSelection" : "' + _addOnSelect + '", "commandSelection" : "' + _consoleCmdExprValue + '"}';
var stringToSend = " <img class='preLoader' src='images/preloader.gif' title = 'Processing request'/>";
const _toolTipContentHeader = ' <div>' +
' <strong>Server Name    <span class="tooltip" data-title="<strong>hey</strong>" style="color: aqua">%HDRITEM0%</span></strong><br />' +
' <strong>Server IP Address    <span style="color: aqua">%HDRITEM1%</span></strong><br />' +
' <strong>Server #Processors    <span style="color: aqua">%HDRITEM2%</span></strong><br />' +
' <strong>Version    <span style="color: aqua">%HDRITEM3_1%</span></strong><br />' +
' <strong>Build Ref    <span style="color: aqua">%HDRITEM3_2%</span></strong><br />' +
// ' <strong>Build Date    <span style="color: aqua">%HDRITEM3_3%</span></strong><br />' +
' <strong>Configs Count    <span style="color: aqua">%HDRITEM4%</span></strong><br />' +
' <strong>Master Config    <span style="color: aqua">%HDRITEM5%</span></strong><br />' +
' </div>';
const _toolTipContentLine = ' <div>' +
' <strong>Server Name    <span style="color: aqua">%LNITEM0%</span></strong><br />' +
' <strong>Config Process ID    <span style="color: aqua">%LNITEM1%</span></strong><br />' +
' <strong>Config Status    <span style="color: aqua">%LNITEM2%</span></strong><br />' +
' <strong>Config Java Version    <span style="color: aqua">%LNITEM3%</span></strong><br />' +
' <strong>Version    <span style="color: aqua">%LNITEM4_1%</span></strong><br />' +
' <strong>Build Ref    <span style="color: aqua">%LNITEM4_2%</span></strong><br />' +
// ' <strong>Build Date    <span style="color: aqua">%LNITEM4_3%</span></strong><br />' +
' <strong>iBSE Port (If Enabled)    <span style="color: aqua">%LNITEM5%</span></strong><br />' +
' <strong>Master Config    <span style="color: aqua">%LNITEM6%</span></strong><br />' +
' <strong>Registry    <span style="color: aqua">Here</span></strong><br />' +
' <strong>Blue    <span style="color: aqua">Here</span></strong><br />' +
' <strong>Runtime    <span style="color: aqua">Here</span></strong><br />' +
' </div>';
$.ajax({
type: "POST",
url: `http://${iSMHost}:${iSMPort}/${urlExtension}`,
data: dataString,
timeout: 60000 * 30, //60000 milliseconds * 30 = 30 minutes
async: true,
contentType: "application/json",
cache: false,
beforeSend: function () {
$(".terminal .top").addClass('color-change-5x');
$('.terminal .responseBody').html("");
},
success: function (result) {
if (_addOnSelect == 'ConfigsList') {
var h1 = $('<h1 class="responseTitleText">Launch Pad</h1>')
var tabDiv = $('<div id="tabsID"></div>')
var prodTab = $('<div class="tab-container" data-tab-index="0"></div>');
var testTab = $('<div class="tab-container" data-tab-index="1" style="display:none;"></div>');
$('.terminal .responseBody').append(h1);
$('.terminal .responseBody').append(prodTab);
$('.terminal .responseBody').append(testTab);
for (var i = 0; i < result.length; ++i) {
var div = $('<div>'), ulForTest = $('<ul>'), ulForProd = $('<ul>');
var _tempHeaderItem = result[i];
var _tempInstanceFlag = (_tempHeaderItem.host).split(':')[1];
var _tempHostEnvironment = (_tempHeaderItem.host).split(':')[0]
_tempHostEnvironment = ((/p.me.com$/).test(_tempHostEnvironment)) ? 'Prod' : 'Test';
var replacementsForHDR = {
"%HDRITEM0%": _nvl(_tempHeaderItem.host.replace('.me.com', '')),
"%HDRITEM1%": _nvl(_tempHeaderItem.serverIP),
"%HDRITEM2%": _nvl(_tempHeaderItem.processorsCount),
"%HDRITEM3_1%": _nvl(_tempHeaderItem.configs[0].Version),
"%HDRITEM3_2%": _nvl(_tempHeaderItem.configs[0].Build),
// "%HDRITEM3_3%": _nvl(_tempHeaderItem.configs[0].BuildDate),
"%HDRITEM4%": _nvl(('Active: ' + _tempHeaderItem.activeConfigsCount + '/ Inactive: ' + _tempHeaderItem.inActiveConfigsCount)),
"%HDRITEM5%": _nvl(_tempHeaderItem.master)
};
var _toolTipContentHeaderInstance = _toolTipContentHeader.replace(/%\w+%/g, function (all) {
return replacementsForHDR[all] || all;
});
_tempInstanceFlag = (_tempInstanceFlag == '19') ? '1st' : (_tempInstanceFlag == '29') ? '2nd' : (_tempInstanceFlag == '39') ? '3rd' : (_tempInstanceFlag == '49') ? '4th' : '1st?';
if(_tempHostEnvironment == 'Prod'){
ulForProd.append("<li class='tooltip' data-title='" + _toolTipContentHeaderInstance + "'>" + ((_tempHeaderItem.host).split('.')[0]).replace(".me.com", "") + " " + _tempInstanceFlag + "</li>")
}else{
ulForTest.append("<li class='tooltip' data-title='" + _toolTipContentHeaderInstance + "'>" + ((_tempHeaderItem.host).split('.')[0]).replace(".me.com", "") + " " + _tempInstanceFlag + "</li>")
}
for (var j = 0; j < _tempHeaderItem.configs.length; ++j) {
var _tempLineItem = _tempHeaderItem.configs[j];
var replacementsForLN = {
"%LNITEM0%": _nvl(_tempHeaderItem.host.replace('.me.com', '')),
"%LNITEM1%": _nvl(_tempLineItem.processID),
"%LNITEM2%": _nvl(_tempLineItem.status),
"%LNITEM3%": _nvl(_tempLineItem.javaVersion),
"%LNITEM4_1%": _nvl(_tempLineItem.Version),
"%LNITEM4_2%": _nvl(_tempLineItem.Build),
// "%LNITEM4_3%": _nvl(_tempLineItem.BuildDate),
"%LNITEM5%": _nvl(((_tempLineItem.ibsePort.length > 0) ? _tempLineItem.ibsePort : 'NA')),
"%LNITEM6%": _nvl(_tempHeaderItem.master),
"%LNITEM7%": _nvl('http://' + _tempHeaderItem.host + '/' + _tempLineItem.config + '&filter=on'),
"%LNITEM8%": _nvl('http://' + _tempHeaderItem.host + '/yes?configuration=' + _tempLineItem.config),
"%LNITEM9%": _nvl('http://' + _tempHeaderItem.host + '/yes?configuration%7D_' + _tempLineItem.config)
};
var _toolTipContentLineInstance = _toolTipContentLine.replace(/%\w+%/g, function (all) {
return replacementsForLN[all] || all;
});
if(_tempHostEnvironment == 'Prod'){
div.append(ulForProd.append("<li class='tooltip' data-title='" + _toolTipContentLineInstance + "'>" + _tempLineItem.config + "</li>"));
$('#tabLink').show();
$('.terminal .responseBody .tab-container[data-tab-index=0]').append(div.addClass('tracking-in-expand-fwd'));
}else{
div.append(ulForTest.append("<li class='tooltip' data-title='" + _toolTipContentLineInstance + "'>" + _tempLineItem.config + "</li>"));
$('#tabLink').show();
$('.terminal .responseBody .tab-container[data-tab-index=1]').append(div.addClass('tracking-in-expand-fwd'));
}
}
}
}
tippy('.tooltip', {
theme: 'custom',
content: function (reference) {
const htmlContent = reference.getAttribute('data-title');
return htmlContent;
},
interactive: true,
allowHTML: true,
multiple: true
});
popperOptions: { strategy: 'fixed' };
},
error: function (x, t, m) {
$('.terminal .responseBody').html("<p class='error fade-in-fwd'>Something went wrong at the server. Thats all I know! :-(</p>");
},
complete: function (x, t, m) {
$('.terminal .title').html('response pane');
$(".terminal .top").removeClass('color-change-5x');
}
});
return false;
}
the relevant CSS styling info
.tippy-box[data-theme~="custom"] span {
float: right;
}
.tippy-box[data-theme~="custom"] {
width: max-content;
}
Owing to the complexity of the application, I couldn't create a repro on a fiddle/etc. The first tooltip gets displayed well, while the nested does not get displayed.
result:
Any help would be much appreciated.
If the nested tooltip is invoked using data-tippy-content with html, the value gets displayed but the HTML gets displayed raw, meaning, HTML tags appear as-is.

How can I filter null or undefined values from an ajax call?

I'm trying to create a simple class directory for my kid's class. I have a Array of students in JSON format and wrote an AJAX call for the kids' names, and parents information. But some don't have two parents or two sets of contact information? I have tried "if (studentData !== null) {
show the data} but that doesn't work.
function showStudents() {
var currentURL = window.location.origin;
$.ajax({ url: currentURL + '/api/students', method: 'GET'})
.then(function(studentData) {
console.log("------------------------------------");
console.log("URL: " + currentURL + "/api/students");
console.log("------------------------------------");
// Here we then log the NYTData to console, where it will show up as an object.
console.log(studentData);
console.log("------------------------------------");
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + studentData[i].parent1 + ' & ' + studentData[i].parent2 +' </li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
});
}
It sounds like it's the parent1 or parent2 properties that might not exist, and the contact1 or contact2 properties that might not exist. It doesn't make sense to test if the entire response is null - just check those properties instead. For example:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
// Start of changes
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
// End of changes
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
Your script structure could be improved too - unless each card's id is particularly important, it would make more sense to use a class instead of unique ids for every single element, or perhaps to leave it off entirely if you're only using it to select the newly created container. You already have a reference to the element you just created with studentSection, so just reference that variable again. You can also use method chaining to reduce your syntax noise:
CSS:
.card {
width: 25rem;
}
(that will keep you from having to manually set the width of each created element in your JS)
JS loop:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
$('#studentSection').append(studentSection);
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
studentSection.addClass('card')
.append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>')
.append('<ul class="list-group list-group-flush>')
.append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
studentSection.append('</ul>');
.append('</div>');
}
(Or, even better, use template literals instead)

How do I replace a string in a parent page from a JS created childpage?

I am creating a dynamic list with JS
var obj = JSON.parse(Agent212);
var i;
var serie = "Agent212";
for (i = 0; i < obj.strips.length; i++) {
if (obj.strips[i].Collectie == "0") {
document.write("<li><a onclick='newPage(" + obj.strips[i].Nummer + "," + serie + ")' style = 'color:orange'>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel + "</a></li>");
}
else if (obj.strips[i].Collectie == "2") {
document.write("<li><a onclick='newPage(" + obj.strips[i].Nummer + "," + serie + ")' style = 'color:red'>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel + "</a></li>");
}
else {
document.write("<li><a class='ToHide' onclick='newPage(" + obj.strips[i].Nummer + "," + serie + ")'><strike>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel + "</strike></a></li>");
}
}
when I click on an item in the list, I create a childpage
function newPage(StripNum, SerieNaam) {
var obj = JSON.parse(SerieNaam);
var i;
var x = StripNum;
for (i = 0; i < obj.strips.length; i++) {
if (obj.strips[i].Nummer == x) {
if (obj.strips[i].Collectie == 0) {
var myWindow = window.open();
myWindow.document.writeln('<html>');
myWindow.document.writeln('<head>');
myWindow.document.writeln('<meta name="viewport" content="width=device-width, initial-scale=1">');
myWindow.document.writeln('<link rel="stylesheet" href="./css/W3CSS.css">');
myWindow.document.writeln('<scr' + 'ipt>');
myWindow.document.writeln('function windowClose(){');
myWindow.document.writeln('window.close();}'); **
myWindow.document.writeln('function ToevoegenVerzameling(){'); **
myWindow.document.writeln('window.alert("toegevoegd aan verzameling");');
myWindow.document.writeln('window.close();');
myWindow.document.writeln('}');
myWindow.document.writeln('</scr' + 'ipt>');
myWindow.document.writeln('</head>');
myWindow.document.writeln('<body>');
myWindow.document.writeln('<div class="w3-container w3-display-topmiddle">');
myWindow.document.writeln('<div class="w3-card-16 w3-round-xlarge" style="width:100%">');
myWindow.document.writeln('<a onclick="windowClose();"><center><img src="' + obj.strips[i].Link + obj.strips[i].Nummer + '.jpg"></center></a>');
myWindow.document.writeln('<div class="w3-container w3-margin-top">');
myWindow.document.writeln('<center><B>Nummer: </B><I>' + obj.strips[i].Nummer + '</I></center>');
myWindow.document.writeln('<center><B>Titel: </B><I>' + obj.strips[i].Titel + '</I></center>');
myWindow.document.writeln('<center><button onclick="ToevoegenVerzameling()" class="w3-btn w3-light-grey w3-border w3-border-black w3-round-xlarge w3-margin-top w3-margin-bottom" style="width:100%"><h2><b>Toevoegen</b></h2></button></center>');
myWindow.document.writeln('</div>');
myWindow.document.writeln('</div>');
myWindow.document.writeln('</div>');
myWindow.document.writeln('</body>');
myWindow.document.writeln('</html>');
}
all of the above does work, but know I want to ad a replace function to ToevoegenVerzameling().
I've tried with adding this piece of code.
myWindow.document.writeln('if (window.opener != null && !window.opener.closed){');
myWindow.document.writeln('var str = "<li><a onclick='
newPage(" + obj.strips[i].Nummer + ", " + serie + ")
' style = '
color: orange '>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel +"</a></li>";');
myWindow.document.writeln('str.replace("<a onclick='
newPage(", " < a class = 'ToHide'
onclick = 'newPage(");'); myWindow.document.writeln('str.replace("style = '
color: orange '>", "><\strike>");'); myWindow.document.writeln('str.replace("</a>", "</strike></a>");}');
But I can't get it to work, Were am I making a mistake in this?

Yahoo finance xchange - taking the last update time

I'm doing a query on Yahoo finance xchange, but seems the time of update is not the most updated. Seems random, for each refresh, this value change, sometimes most updated, and sometimes less updated.
There is a way to always get the last time it was updated ?
Thank you.
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDUSD%22%2C%22USDEUR%22%2C%20%22USDJPY%22%2C%20%22USDCNY%22%2C%20%22USDGBP%22%2C%20%22USDBRL%22%2C%20%22EUREUR%22%20%2C%22EURUSD%22%2C%20%22EURJPY%22%2C%20%22EURCNY%22%2C%20%22EURGBP%22%2C%20%22EURBRL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=", function (data) {
var indices = '<p style=\"border:1px solid #ccc; width:auto; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[0].Name + '</strong> ' + money(data.query.results.rate[0].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[1].Name + '</strong> (Fechamento ' + money(data.query.results.rate[1].Rate) + ') - ' + data.query.results.rate[1].Date + ' - ' + data.query.results.rate[1].Time + '</p>' +
'<p><strong>' + data.query.results.rate[2].Name + '</strong> (Fechamento ' + money(data.query.results.rate[2].Rate) + ') - ' + data.query.results.rate[2].Date + ' - ' + data.query.results.rate[2].Time + '</p>' +
'<p><strong>' + data.query.results.rate[3].Name + '</strong> (Fechamento ' + money(data.query.results.rate[3].Rate) + ') - ' + data.query.results.rate[3].Date + ' - ' + data.query.results.rate[3].Time + '</p>' +
'<p><strong>' + data.query.results.rate[4].Name + '</strong> (Fechamento ' + money(data.query.results.rate[4].Rate) + ') - ' + data.query.results.rate[4].Date + ' - ' + data.query.results.rate[4].Time + '</p>' +
'<p><strong>' + data.query.results.rate[5].Name + '</strong> (Fechamento ' + money(data.query.results.rate[5].Rate) + ') - ' + data.query.results.rate[5].Date + ' - ' + data.query.results.rate[5].Time + '</p>' +
'<p style=\"border:1px solid #ccc; width:auto; margin:20px 0 0; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[6].Name + '</strong> ' + money(data.query.results.rate[6].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[8].Name + '</strong> (Fechamento ' + money(data.query.results.rate[8].Rate) + ') - ' + data.query.results.rate[8].Date + ' - ' + data.query.results.rate[8].Time + '</p>' +
'<p><strong>' + data.query.results.rate[7].Name + '</strong> (Fechamento ' + money(data.query.results.rate[7].Rate) + ') - ' + data.query.results.rate[7].Date + ' - ' + data.query.results.rate[7].Time + '</p>' +
'<p><strong>' + data.query.results.rate[9].Name + '</strong> (Fechamento ' + money(data.query.results.rate[9].Rate) + ') - ' + data.query.results.rate[9].Date + ' - ' + data.query.results.rate[9].Time + '</p>' +
'<p><strong>' + data.query.results.rate[10].Name + '</strong> (Fechamento ' + money(data.query.results.rate[10].Rate) + ') - ' + data.query.results.rate[10].Date + ' - ' + data.query.results.rate[10].Time + '</p>' +
'<p><strong>' + data.query.results.rate[11].Name + '</strong> (Fechamento ' + money(data.query.results.rate[11].Rate) + ') - ' + data.query.results.rate[11].Date + ' - ' + data.query.results.rate[11].Time + '</p>';
$('#info').html(indices);
});
money = function (n) {
var
c = 4,
d = ',',
t = '.',
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
Well, I ended up constructing a date for each element in the array (map) and then filtering them to the oldest date (reduce)
what do you want to do with this date, I am not sure but here it is...
UPDATED
updated to return full JSON record containing the latest date/time stamp (instead of returning only the latest date)
// sample response
var response = {"query":{"count":12,"created":"2016-04-29T20:13:39Z","lang":"en-us","results":{"rate":[{"id":"USDUSD","Name":"USD/USD","Rate":"1.0000","Date":"N/A","Time":"N/A","Ask":"1.0000","Bid":"1.0000"},
{"id":"USDEUR","Name":"USD/EUR","Rate":"0.8775","Date":"4/29/2016", "Time":"12:38pm","Ask":"0.8777","Bid":"0.8775"},{"id":"USDJPY","Name":"USD/JPY","Rate":"107.3910","Date":"4/29/2016","Time": "2:55pm","Ask":"107.3940","Bid":"107.3910"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.4868","Date":"4/29/2016","Time":"12:49pm","Ask":"6.4878","Bid":"6.4868"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6843","Date":"4/29/2016","Time":"1:15pm","Ask":"0.6844","Bid":"0.6843"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.4492","Date":"4/29/2016","Time":"3:33pm","Ask":"3.4496","Bid":"3.4492"},{"id":"EUREUR","Name":"EUR/EUR","Rate":"1.0000","Date":"1/29/2016","Time":"8:26am","Ask":"1.0002","Bid":"0.9998"},{"id":"EURUSD","Name":"EUR/USD","Rate":"1.1443","Date":"4/29/2016","Time":"3:08pm","Ask":"1.1443","Bid":"1.1443"},{"id":"EURJPY","Name":"EUR/JPY","Rate":"122.5650","Date":"4/29/2016","Time":"4:00pm","Ask":"122.6200","Bid":"122.5100"},{"id":"EURCNY","Name":"EUR/CNY","Rate":"7.4054","Date":"4/29/2016","Time":"2:08pm","Ask":"7.4070","Bid":"7.4037"},{"id":"EURGBP","Name":"EUR/GBP","Rate":"0.7836","Date":"4/29/2016","Time":"3:22pm","Ask":"0.7837","Bid":"0.7836"},{"id":"EURBRL","Name":"EUR/BRL","Rate":"3.9637","Date":"4/29/2016","Time":"4:28pm","Ask":"3.9679","Bid":"3.9595"}]}}};
//console.log(response.query.results.rate);
var times = response.query.results.rate.map(function(elem){
if( elem.Time === 'N/A' || elem.Time === 0){
elem.fullDateTimeStamp = elem.Time;
//console.log(elem);
return elem;
}
// create full date from the time (using time and date combined)
// 1) is it AM or PM
var elemIsPm = (elem.Time.substring(elem.Time.length-2).indexOf("am") == -1);
// 2) remove AM/PM and get hour:min into array
var elemArr = elem.Time.substring(0, elem.Time.length-2).split(":");
// 3) add 12 hours if PM and not noon
if( elemIsPm && elemArr[0] != 12){
elemArr[0] = parseInt(elemArr[0]) + 12;
}
//console.log(elemArr[0]);
// 4) however, if it is 12, we deduct 12 if it's not PM
if( elemArr[0] == 12 && !elemIsPm ){
elemArr[0] = elemArr[0] - 12;
}
// 5) create date object
var elemDateString = elem.Date;
var elemDateOnly = new Date(elemDateString);
//console.log(elemDateOnly);
var elemTS = new Date(elemDateOnly.getFullYear(), elemDateOnly.getMonth(), elemDateOnly.getDate(), elemArr[0], elemArr[1], 0, 0);
elem.fullDateTimeStamp = elemTS;
// console.log(elem);
// 4) return
return elem;
});
console.log( times );
var lastOne = times.reduce(function(prevVal, elem) {
// console.log('p');
// console.log(prevVal );
// console.log('e');
// console.log(elem );
if( prevVal === 'N/A' || prevVal === 0 || prevVal.Time){
return elem;
}
//console.log(prevVal.fullDateTimeStamp);
return (prevVal.fullDateTimeStamp < elem.fullDateTimeStamp)? elem : prevVal;
}, 0);
document.getElementById('latest').innerHTML = JSON.stringify(lastOne);
console.log('====> ');
console.log( JSON.stringify(lastOne.fullDateTimeStamp) );
Last date:
<div id='latest'></div>

JSON and Tumblr

Okay, so I'm trying to create a "Order Posts by Type" using jQuery JSON to get the data... All the post types works in Chrome, Safari, FF. But in IE, video / audio posts will not display (perhaps something to do with the embedding?) when I filter through the posts using JSON.
Does anyone have a clue what's going on?! Here's the code:
<script>
$('#order_by ul li').find('a').click(function() {
var postType = this.className;
var count = 0;
byCategory(postType);
return false;
function byCategory(postType, callback) {
$.getJSON('{URL}/api/read/json?type=' + postType + '&callback=?', function(data) {
var article = [];
$.each(data.posts, function(i, item) {
// i = index
// item = data for a particular post
switch(item.type) {
case 'photo':
article[i] = '<div class="post_wrap"><div class="photo"><a href="'
+ item.url
+ '" title="View Full Post" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/0yplawef6/link_photo.png" /></a><a href="'
+ item.url
+ '"><img src="'
+ item['photo-url-1280']
+ '"alt="image" /></a></div></div>';
count = 1;
break;
case 'video':
article[i] = '<div class="post_wrap"><div class="video"><a href="'
+ item.url
+ '" title="View Full Post" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/FWAlawenw/link_video.png" /></a><span><br />'
+ item['video-player']
+ '</span><div class="video_desc">'
+ item['video-caption']
+ '</div></div></div>';
count = 1;
console.log(article[i]);
break;
case 'audio':
article[i] = '<div class="post_wrap"><div class="audio"><a href="'
+ item.url
+ '" title="View Full Post" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/e8Zlawemi/link_audio.png" /></a><h2 class="heading"><a href="'
+ item.url + '">'
+ item['id3-artist']
+' - '
+ item['id3-title']
+ '</a></h2><div class="player"><br />'
+ item['audio-player']
+ '<p>' + item['id3-artist'] + ' - ' + item['id3-title'] + '</p>'
+ '<p>' + item['audio-plays'] + ' plays</p>'
+ '</div><div class="audio_desc">'
+ item['audio-caption']
+ '</div><div class="clear"></div></div></div>';
count = 1;
break;
case 'regular':
article[i] = '<div class="post_wrap"><div class="regular"><a href="'
+ item.url
+ '" title="View Full Post" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/LH3laweb7/link_text.png" /></a><h2 class="heading"><a href="'
+ item.url
+ '">' + item['regular-title']
+ '</a><div class="description_container">'
+ item['regular-body']
+ '</div></div></div>';
count = 1;
break;
case 'quote':
article[i] = '<div class="post_wrap"><div class="quote"><a href="'
+ item.url
+ '" title="View Full Post" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/1Lwlaweh7/link_quote.png" /></a><blockquote>'
+ item['quote-text']
+ '</blockquote><cite>- '
+ item['quote-source']
+ '</cite></div></div>';
count = 1;
break;
case 'conversation':
article[i] = '<div class="post_wrap"><div class="chat"><a href="'
+ item.url
+ '" title="View Full Post" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/NZ9lawekt/link_chat.png" /></a><h2 class="heading"><a href="'
+ item.url
+ '">' + item['conversation-title']
+ '</a></h2></div></div>';
count = 1;
break;
case 'link':
article[i] = '<div class="post_wrap"><div class="link"><a href="'
+ item.url
+ '" title="View Full Post" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/G1zlaweir/link_link.png" /></a><h2 class="heading"><a href="'
+ item['link-url']
+ '">' + item['link-text']
+ '</a></h2></div></div>';
count = 1;
break;
default:
alert('No Entries Found.');
};
}) // end each
if (!(count == 0)) {
$('#main_content')
.fadeOut('fast')
.html('<div class="post_wrap"><div class="regular"><h2 class="heading">Displaying '
+ postType
+ ' Posts Only</h2></div></div>'
+ '<div class="post_wrap"'
+ article.join('')
+ '</div>'
).fadeIn('fast')
$('div.video').each(function() {
var video_container_height = $(this).innerHeight();
video_container_height = (video_container_height - 60)
$(this).children('div.video_desc').css(
{'position': 'absolute',
'top': '40px',
'right': '20px',
'width': '380px',
'height': video_container_height}
).jScrollPane({
verticalGutter: 25
});
});
$('div.audio div.audio_desc').each(function() {
var container_width = $('div.audio').outerWidth(true);
var player_width = $('div.audio div.player').outerWidth(true);
var audio_desc_width = (container_width - player_width);
$(this).css(
{'position': 'absolute',
'top': '75px',
'right': '20px',
'height': '125px',
'width': (audio_desc_width - 50 /*The size of the left and right margin*/)})
.jScrollPane({
verticalGutter: 25
});
});
} else {
$('#main_content')
.fadeOut('fast')
.html('<div class="post_wrap"><div class="regular"><h2 class="heading">Whoops! There are no '
+ postType
+ ' Posts To Display</h2></div></div>'
).fadeIn('fast')
} // end IF
}); // end getJSON
}; // end byCategory
}); // end click
</script>
To check out the live version, head on over to http://minimus.tumblr.com
I think you problem is caused by a tiny error at line 1690:
$('#main_content')
.fadeOut('fast')
.html('<div class="post_wrap"><div class="regular"><h2 class="heading">Displaying '
+ postType
+ ' Posts Only</h2></div></div>'
+ '<div class="post_wrap"' // line 1690: you are missing a '>'
+ article.join('')
+ '</div>'
).fadeIn('fast')

Categories

Resources