This function is displaying images from firebase urls:
function updateTimeline(){
var ul = document.querySelector("#timeline ul");
ul.innerHTML = "";
var db = firebase.database().ref("phoodos/");
var list = db.orderByChild("timeStamp");
list.on("child_added", function(child) {
var selfie = child.val();
// Retrieve the image file
var storageRef = firebase.storage().ref();
var imageRef = storageRef.child(selfie.path);
imageRef.getDownloadURL().then(function(url){
var li = "<li><figure>";
li += "<img src='" + url + "' width='100%' alt='Phoodo'>";
li += "<figcaption>By " + selfie.user + ": " + selfie.timeStamp + "</figcaption>";
li += "</figure></li>";
ul.innerHTML += li;
})
});
}
Results of orderByChild are sorted, but results from getDownloadURL() are not sorted.
How can I sort the images retrieved by getDownloadURL() before adding to my html?
One trick is to insert the HTML in the correct order:
var ul = document.querySelector("#timeline ul");
ul.innerHTML = "";
var db = firebase.database().ref("phoodos/");
var list = db.orderByChild("timeStamp");
list.on("child_added", function(child) {
var selfie = child.val();
// Retrieve the image file
var storageRef = firebase.storage().ref();
var imageRef = storageRef.child(selfie.path);
var li = document.createElement("li");
ul.appendChild(li); // this ensures the <li> is in the right order
imageRef.getDownloadURL().then(function(url){
var html = "<figure>";
html += "<img src='" + url + "' width='100%' alt='Phoodo'>";
html += "<figcaption>By " + selfie.user + ": " + selfie.timeStamp + "</figcaption>";
html += "</figure>";
li.innerHTML = html;
})
});
Related
I have a page in which I want to put a Name, Image URL, Description in alert and display this info in a loop. But it's not working for me!
Here is the code
let nameArr = [companyName];
let logoArr = [companyLogo];
let logoImgList = [];
let companyList = "";
let aboutCompanyArr = [aboutCompany];
for(let i=0; i < logoArr.length; i++){
logoImgList[i] = "<img src='" + logoArr[i] + "' width=150 height=150>"; //you don't need to add directory here, Image URLs should be direct!
}
for(let i=0; i < nameArr.length; i++){
companyList += "<div class='companyList'>" + logoImgList[i] + "<br>" + nameArr[i] + "<br>" + aboutCompanyArr[i] + "</div>";
}
document.getElementById("companyList").innerHTML = companyList;
var nameArr=[];
var logoArr=[];
var aboutCompanyArr=[];
function addCompany(){
let companyName = prompt("Enter the company name:");
let companyLogo = prompt("Copy and paste URL company logo:");
let aboutCompany = prompt("Say a little about the company:");
nameArr.push(companyName);
logoArr.push(companyLogo);
aboutCompanyArr.push(aboutCompany);
let logoImgList = [];
let companyList = "";
//let companyImgList = [];
for(let i=0; i < logoArr.length; i++){
logoImgList[i] = "<img src='" + logoArr[i] + "' width=150 height=150/>"; //you don't need to add directory here, Image URLs should be direct!
}
for(let i=0; i < nameArr.length; i++){
companyList += "<div class='companyList'>" + logoImgList[i] + "<br>" + nameArr[i] + "<br/>" + aboutCompanyArr[i] + "</div>";
}
document.getElementById("companyList").innerHTML = companyList;
}
Check this.
I've updated the code.
I am working on a website and I am looking to make the recipes pages dynamic. I created a JSON test database, created a JS file that retrieves values from the JSON file and displays them in appropriate divs on the page.
What i want to do is be able to choose the respectful JSON for each recipe and display it on the same page when a user clicks a link in the sidebar without having to create a ton of blank HTML pages with the same divs.
Below is my code. Hoping someone can help guide me thanks!
(function() {
'use strict';
var url = 'my json url';
$.getJSON(url, function(json) {
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
});
})();
new code`(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('#pasta').click(function(){
$('#recipeIngredients').empty();
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = '';
$.getJSON(url,callback);
})();`
to achieve code reusability , try calling the $.getJSON() with a reusable function (callback) on click of the link in the sidebar
(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
.... //rest of the code
...
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('.sidebarLink').click(function(){
$('#recipeIngredients').empty()
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = 'my json url';
$.getJSON(url,callback);
})();
I have a folder with images that have long filenames, but they all have unique product ID numbers at the beginning
e.g. 1023-Very-Long-Image-Name.jpg.
What I'm trying to do is to get full image filename into my javascript, by just using this unique ID number.
e.g. I need to find an image with ID 1023, which is this one - 1023-Very-Long-Image-Name.jpg
All unique IDs stored in JSON database. So below is an example of my code:
$('.choose-range-cta').click(function () {
var rowID = $(this).attr("id");
var stylesTable = JSON.parse(stylesDB);
var styleHTML = "";
for (var i = 0; i < stylesTable.length; i++) {
if (stylesTable[i].collectionID == rowID) {
var blockTitle = stylesTable[i].styleName;
var blockPrice = stylesTable[i].fromPrice;
var blockSize = stylesTable[i].size;
var blockImageID = stylesTable[i].frontImageID;
styleHTML += "<div class=\"col-lg-4 style-block\"><span class=\"style-name\">" + blockTitle + "</span><span class=\"from-price\">from £" + blockPrice + "</span><span class=\"cta\">Select</span><div class=\"img-box\"><img src=\"" + ImagePath + blockImageID +"\"></div><span class=\"copy\">" + blockSize + "</span></div>";
}
}
$('#style-list').html(styleHTML);
});
Assuming your list is an array, use filter:
var imageArray = [
'1021-Don-Long-Image-Name.jpg',
'1022-Very-Long-Image-Name.jpg',
'1023-Dan-Long-Image-Name.jpg',
'1024-BobLong-Image-Name.jpg'
];
function getName(data, id) {
return data.filter(function (el) {
return el.substring(0, 4) === id;
})[0];
}
var name = getName(imageArray, '1023'); // 1023-Dan-Long-Image-Name.jpg
DEMO
I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?
EDIT: I got it working! It turned out that I had written innerHtml instead of innerHTML. I This topic can be closed.
I am trying to use JS to put the link most recently clicked by a userinto a table row where a row is created each time a link is clicked. The list of links shown is also generated using JS.
The problem I am having is that when I click a link, the table is created with an empty row.
Here is the JS.
function processLinks()
{
var linksList = document.links; // get the document's links
var contents = "";
for ( var i = 0; i < linksList.length; ++i )
{
var currentLink = linksList[ i ];
contents += "<p style =\"background-color:red\"><a href='" + currentLink.href + "'
target='_blank' id='link" + i + "'>" +
currentLink.innerHTML + "</a></p>";
}
// if user click link var currentLink = linksList[ index of link user clicked ];
//create table
//document.getElementById("link + index to specify element 0,1,2,3, etc for
//id").onclick
document.getElementById( "links" ).innerHTML = contents;
} // end function processLinks
function insertLink(e)
{
var linksList = document.links; // get the document's links
var contents = "";
for (var i = 0; i < linksList.length; ++i)
{
if(document.getElementById("link" + i) )
{
var currentLink = linksList[i];
contents += "<p><a href='" + currentLink.href + "' target='_blank'
id='link" + i + "'>" +
currentLink.innerHTML + "</a></p>";
tbody = document.getElementById("tableBody");
var row = document.createElement("tr");
var cell = document.createElement("td");
cell.innerHtml = contents;
row.appendChild(cell);
tbody.appendChild(row);
}
}
document.getElementById("tableBody").onclick = function(){insertLink()};
}
document.addEventListener("click", insertLink, false);
window.addEventListener( "load", processLinks, false );