Creating new HTML images using a For loop through an array of image URLs - arrays

I have an array of 40 different image URLs being returned from an AJAX request. I'm trying to create a new HTML image element for each URL in the array using a For loop, as seen in the below code. For some reason, it's only displaying the image at the first URL and that's it. Any idea why the other 39 aren't showing up?
$(document).ready(function() {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'https://****/images',
success: function(data) {
console.log(data);
let container = document.getElementById('feed');
let image = document.createElement("img");
for (let i = 0; i < data.length; i++) {
image.setAttribute('src', data[i]);
container.appendChild(image);
}
}
});
});
<body>
<div id="feed">
</div>
</body>

Try to create the element inside the loop.
for (let i = 0; i < data.length; i++) {
let image = document.createElement("img");
image.setAttribute('src', data[i]);
container.appendChild(image);
}

The way to create images is with new Image() and when appending multiple nodes to the DOM at once, it's better to first append the image nodes into a document fragment, and only when all the images have been appended to the fragment, then append the fragment itself into the Document (prevents redundant repaints)
// dummy data
const data = ['http://placekitten.com/100/100',
'http://placekitten.com/100/150',
'http://placekitten.com/100/180',
'http://placekitten.com/100/200']
// create a dumpster-node for the images to reside in
const fragment = document.createDocumentFragment();
// iterate the data and create <img> elements
data.forEach(url => {
let image = new Image()
image.src = url;
fragment.appendChild(image);
})
// dump the fragment into the DOM all the once (FTW)
document.body.appendChild(fragment);
I've used Array forEach iterator in my example, because it's easier in my opinion, but you can use a for loop (or for..of loop)

Related

Loop Object and Array when Array is inside of an Object

I am using a query to receive a JSON response. I would like to loop each object (VGF, SSR, BCV, etc..) and output them to premade divs, then the arrays within those objects will loop and create divs within that matching object container.
This is a shortened down version of what I have, and it works mostly. (hopefully, I haven't screwed it up here).
The problem is I have to repeat the searchresult function by copying and pasting the entire function for each object (VGF, SSR, BCV, etc). I would really like to learn how to loop this and not have the same code pasted more than a dozen times.
If I have messed up or left something out of this question, please let me know and I will take care of it.
Here is my ajax request and javascript. I know my problem lies within this loop. I have tried to do a loop inside of a loop, etc. But, when I do that I get no results at all. I am baffled and ready to learn.
$(function getData() {
$("#searchbtn").click(function () {
$.ajax({
url: "action.php",
type: "POST",
data: {},
dataType: "json",
success: function (response) {
console.log(response);
searchresult(response);
}
});
});
});
let searchresult = function(response) {
let container = document.getElementById('VGFresults');
let output = "";
for (let j = 0; j < response.length; j++) {
if (response[j].rcode == "VGF") {
output +=
`<div id="person${response[j].code}">
<p>${response[j].firstname} ${response[j].lastname}</p>
</div>`
}
$(container).html(output);
}
};
Here is my response (Same layout as I am currently receiving but shortened the objects in the arrays).
response =
{"VGF":
[{"code":"TU","rcode":"VGF","firstname":"Tom","lastname":"Riddle"},
{"code":"AZ","rcode":"VGF","firstname":"Harry","lastname":"Potter"},
{"code":"FR","rcode":"VGF","firstname":"Hermoine","lastname":"Granger"}],
"SSR":
[{"code":"HG","rcode":"SSR","firstname":"Walt","lastname":"Disney"},
{"code":"TR","rcode":"SSR","firstname":"H.R.","lastname":"Pickins"},
{"code":"ED","rcode":"SSR","firstname":"Tom","lastname":"Ford"}],
"BCV":
[{"code":"YH","rcode":"BCV","firstname":"Tom","lastname":"Clancy"},
{"code":"RS","rcode":"BCV","firstname":"Robin","lastname":"Williams"},
{"code":"AB","rcode":"BCV","firstname":"Brett","lastname":"Favre"}]}
Here is the HTML that the searchresult function is working with. Currently, it works fine.
To clarify, I would like each object to insert its arrays within the corresponding div. Example:
SSR arrays will go into <div id="SSRresults">
BCV arrays will go into <div id="BCVresults">
From there, each array will create a div within that *results div for each array.
<div id="VGFresults">
<div id="VGFheader">This is the VGF Header</div>
<div id="VGFresults">The Javascript Creates Divs for each array here.</div>
</div>
<div id="SSRresults">
<div id="SSRheader">This is the SSR Header</div>
<div id="SSRresults">The Javascript Creates Divs for each array here.</div>
</div>
<div id="BCVresults">
<div id="BCVheader">This is the BCV Header</div>
<div id="BCVresults">The Javascript Creates Divs for each array here.</div>
</div>
Thanks, any help is much appreciated.
I would do like this:
I declare the response as variable (but sure it will work with your ajax response.
var response =
{"VGF":
[{"code":"TU","rcode":"VGF","firstname":"Tom","lastname":"Riddle"},
{"code":"AZ","rcode":"VGF","firstname":"Harry","lastname":"Potter"},
{"code":"FR","rcode":"VGF","firstname":"Hermoine","lastname":"Granger"}],
"SSR":
[{"code":"HG","rcode":"SSR","firstname":"Walt","lastname":"Disney"},
{"code":"TR","rcode":"SSR","firstname":"H.R.","lastname":"Pickins"},
{"code":"ED","rcode":"SSR","firstname":"Tom","lastname":"Ford"}],
"BCV":
[{"code":"YH","rcode":"BCV","firstname":"Tom","lastname":"Clancy"},
{"code":"RS","rcode":"BCV","firstname":"Robin","lastname":"Williams"},
{"code":"AB","rcode":"BCV","firstname":"Brett","lastname":"Favre"}]}
let searchresult = function(response) {
// let container = document.getElementById('VGFresults');
let output = "";
for (var key in response) {
// skip loop if the property is from prototype
if (!response.hasOwnProperty(key)) continue;
var obj = response[key];
let container = document.getElementById(key+'results');
for (var prop in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(prop)) continue;
// your code
//alert(prop + " = " + obj[prop]);
console.log(obj[prop])
output += "<div id="+prop+"><p>"+obj[prop].firstname+" "+ obj[prop].lastname+"</p></div>"
}
}
container.innerText = output;
console.log(output);
};
<div id="VGFresults"></div>
each property VGF, SSR, BCV and so on can be handled now.
EDIT: based on users request, I guess you can edit the selector like this:
let container = document.getElementById(key+'results');

Angular: manipulating trusted HTML before binding

In my Angular app, I receive some HTML as a string from an API and then I want to render it in the page. So I do:
var myHtml = $sce.valueOf(inputString);
return myHtml;
And then I include it in my template:
<div ng-bind-html="myHtml"></div>
This works fine. But before I render it, I also want to make some changes to the text content of the HTML nodes. (I don't want to do this to the original inputString because it's hard to avoid affecting HTML tags.) So I tried:
var myHtml = $sce.valueOf(inputHtml);
// myHtml is an object of type TrustedValueHolderType
// now I want to access the HTML nodes inside it so I do:
for (var i = 0; i < myHtml.length; ++i) {
if (myHtml[i].nodeType === 3) {
myHtml[i].nodeValue = myHtml[i].nodeValue.replace(/a/, 'b');
}
}
return myHtml;
And then include it in my template:
<div ng-bind-html="myHtml"></div>
But this doesn't work because myHtml is not a list of nodes but an object of type TrustedValueHolderType and I cannot access the HTML nodes inside it.

google maps v3 duplicate markers - using an array to manage markers but still get duplicates

I'm not getting it: I have an array to manage my markers I add to a map. When I update the collection, the markers duplicate even though my markers array still only has the correct number of them in it.
I'm sure this is a really simple and stupid mistake on my part - but I'm not seeing it.
m.viewMarkers = function(data){
//ajax call to get latLng, returns an object with 4 markers
showMarkers();
}
function showMarkers(){
g.currentMarkers = []; // setting up my marker array
$.each(g.markersCollection, function(i,item){ // jquery-iterate over the object from the ajax call
g.currentMarkers.push( // adding markers to the array but purposely not drawing them on the map just yet
new google.maps.Marker({
position : new google.maps.LatLng(item.lat, item.lng)
});
);
});
$.each(g.currentMarkers, function(i,item){
if( g.map.getBounds().contains( item.getPosition() ) ){ // checking if this marker is within the viewport
item.setMap(g.map);
}
else {
item.setMap(null); // i don't want to have invisible markers slowing down my map
}
});
console.log(g.currentMarkers.length); // tells me it's 4, just as expected
}
google.maps.event.addListener(g.map, 'dragend', function() {
m.viewMarkers();
});
To me this looks like all is well, but the map keeps drawing 4 new markers on every dragend.... eeek!
Modify your showMarkers() function to this:
function showMarkers(){
//Removing old markers from the Map,if they are exist
if(g.currentMarkers && g.currentMarkers.length !== 0){
$.each(g.currentMarkers, function(i,item){
item.setMap(null);
});
}
g.currentMarkers = []; // setting up my marker array
$.each(g.markersCollection, function(i,item){
var expectedPosition = new google.maps.LatLng(item.lat, item.lng);
//No need to add marker on the Map if it will not visible on viewport,
//so we check the position, before adding
if(g.map.getBounds().contains(expectedPosition)){
g.currentMarkers.push(new google.maps.Marker({
position : expectedPosition
}) );
}
});
}
You can also compare new markers with your stored markers using some of following code (to display stored markers rather than new response marker):
var latlng1,latlng2;
for (var i=0; i< storedmarker.length; i++){
//Removing old markers from the Map,if they are exist with storedmarkers
latlng1 = storedmarker[i].getPosition();
for (var j=0; j< newmarkers.length; j++) {
latlng2 = newmarkers[j].getPosition();
if(latlng1.equals(latlng2)){
newmarkers[j].setMap(null);
}
}
//Set Marker
storedmarker[i].setMap(map);
}

passing an array in a message from content script to background page in google chrome extension

I am writing a Google Chrome extension.
I want to pass a small array from a content script to background page in a message. Can I simply reference the array name or need I construct a JSON object from it first?
Here is the code:
IN THE CONTENT SCRIPT
var req;
var detailWin;
//drag off the f_foto class
var searchResult = document.getElementsByClassName("f_foto");
alert("Found Class f_foto "+searchResult.length+" times.");
//collect profile links
for (var i = 0; i<searchResult.length; ++i)
{
var profileLink=searchResult[i].getElementsByTagName("a");
profileLinks[i]=profileLink[0].href;
// alert(i+1+" of "+searchResult.length+" "+profileLinks[i]+" length of "+profileLinks[i].length);
}
for (var i = 0; i<searchResult.length; ++i)
{
//tell bkgd page to open link
chrome.extension.sendRequest({cmd: "openProfile", url: profileLinks[i]});
//BETTER TO SEND WHOLE ARRAY.
//LIKE THIS? chrome.extension.sendRequest({cmd: "openProfile", urlList: profileLinks});
//OR SHOULD I MAKE A JSON OBJECT OUT OF IT?
}
//IN THE BACKGROUND PAGE
var detailTabId = null;
var profileLinks = new Array();
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.cmd == "openProfile") {
//IF RECEIVING AN ARRAY, PROCESS IT LIKE THIS?
// profileLinks= request.urlList;
// console.log=("Received "+ urlList.length + " links.");
chrome.tabs.create({url: request.url}, function(tab){
//save tab id so we can close this tab later
detailTabId = tab.id;
//profile tab is created, inject profile script
chrome.tabs.executeScript(tab.id, {file: "profile.js"});
});
}
});
An Array is a construct of a JSON object so there is no need to do anything other than what you are doing now.

How to print ExtJS component?

How do I pop up the Print dialog that will print out a component when OK-ed?
var targetElement = Ext.getCmp('PrintablePanelId');
var myWindow = window.open('', '', 'width=200,height=100');
myWindow.document.write('<html><head>');
myWindow.document.write('<title>' + 'Title' + '</title>');
myWindow.document.write('<link rel="Stylesheet" type="text/css" href="http://dev.sencha.com/deploy/ext-4.0.1/resources/css/ext-all.css" />');
myWindow.document.write('<script type="text/javascript" src="http://dev.sencha.com/deploy/ext-4.0.1/bootstrap.js"></script>');
myWindow.document.write('</head><body>');
myWindow.document.write(targetElement.body.dom.innerHTML);
myWindow.document.write('</body></html>');
myWindow.print();
write your extjs printable component into document.
I like Gopal Saini's answer! I took his approach and wrote a function for one of my apps. Here's the code. Tested on FF and Safari. Haven't tried it on IE but it should work.
print: function(el){
var win = window.open('', '', 'width='+el.getWidth()+',height='+el.getHeight());
if (win==null){
alert("Pop-up is blocked!");
return;
}
Ext.Ajax.request({
url: window.location.href,
method: "GET",
scope: this,
success: function(response){
var html = response.responseText;
var xmlDoc;
if (window.DOMParser){
xmlDoc = new DOMParser().parseFromString(html,"text/xml");
}
else{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(html);
}
win.document.write('<html><head>');
win.document.write('<title>' + document.title + '</title>');
var xml2string = function(node) {
if (typeof(XMLSerializer) !== 'undefined') {
var serializer = new XMLSerializer();
return serializer.serializeToString(node);
} else if (node.xml) {
return node.xml;
}
}
var links = xmlDoc.getElementsByTagName("link");
for (var i=0; i<links.length; i++){
win.document.write(xml2string(links[i]));
}
win.document.write('</head><body>');
win.document.write(el.dom.innerHTML);
win.document.write('</body></html>');
win.print();
},
failure: function(response){
win.close();
}
});
}
ExtJS 4.1:
https://github.com/loiane/extjs4-ux-gridprinter
Printing in ExtJS is not paticularly easy. The best resource I've found on making components printable can be found on a Sencha architect's blog. The post describes how to set up custom print renderers for components, and other details about printing. However, this information is for ExtJS 3.x; it's possible that ExtJS 4 has made printing easier.
You can also add a component to be printed to the Ext.window.Window with a modal property set to true and just open a standard print dialog which will only print the desired component.
var view = this.getView();
var extWindow = Ext.create('Ext.window.Window', { modal: true });
extWindow.add(component); // move component from the original panel to the popup window
extWindow.show();
window.print(); // prints only the content of a modal window
// push events to the event queue to be fired on the print dialog close
setTimeout(function() {
view.add(component); // add component back to the original panel
extWindow.close();
}, 0);
Another option to consider is to render the component to an image or pdf. While the pop-up window/print option is nice, some browsers don't print correctly. They tend to ignore background images, certain css properties, etc. To get the component to print exactly the way it appears in the pop-up window, I ended up writing some server side code to transform the html into an image.
Here's what the client code looks like:
print: function(el){
var waitMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
waitMask.show();
//Parse current url to set up the host and path variables. These will be
//used to construct absolute urls to any stylesheets.
var currURL = window.location.href.toString();
var arr = currURL.split("/");
var len = 0;
for (var i=0; i<arr.length; i++){
if (i<3) len+=(arr[i].length+1);
}
var host = currURL.substring(0, len);
if (host.substring(host.length-1)=="/") host = host.substring(0, host.length-1);
var path = window.location.pathname;
if (path.lastIndexOf("/")!=path.length-1){
var filename = path.substring(path.lastIndexOf("/")+1);
if (filename.indexOf(".")!=-1){
path = path.substring(0, path.lastIndexOf("/")+1);
}
else{
path += "/";
}
}
//Start constructing an html document that we will send to the server
var html = ('<html><head>');
html += ('<title>' + document.title + '</title>');
//Insert stylesheets found in the current page. Update href attributes
//to absolute URLs as needed.
var links = document.getElementsByTagName("link");
for (var i=0; i<links.length; i++){
var attr = links[i].attributes;
if (attr.getNamedItem("rel")!=null){
var rel = attr.getNamedItem("rel").value;
var type = attr.getNamedItem("type").value;
var href = attr.getNamedItem("href").value;
if (href.toLowerCase().indexOf("http")!=0){
if (href.toString().substring(0, 1)=="/"){
href = host + href;
}
else{
href = host + path + href;
}
}
html += ('<link type="' + type + '" rel="' + rel+ '" href="' + href + '"/>');
}
}
html += ('</head><body id="print">');
html += (el.dom.innerHTML);
html += ('</body></html>');
//Execute AJAX request to convert the html into an image or pdf -
//something that will preserve styles, background images, etc.
//This, of course, requires some server-side code. In our case,
//our server is generating a png that we return to the client.
Ext.Ajax.request({
url: "/WebServices/Print?action=submit",
method: "POST",
rawData: html,
scope: this,
success: function(response){
var url = "/WebServices/Print?action=pickup&id="+response.responseText;
window.location.href = url;
waitMask.hide();
},
failure: function(response){
win.close();
waitMask.hide();
var msg = (response.responseText.length>0 ? response.responseText : response.statusText);
alert(msg);
}
});
}
Again, this requires some server-side magic to transform the html into an image. In my case, I implemented a "Print" service. Clients submit job requests via the "submit" action and retrieve output products via the "pickup" action.
To convert html to images, I ended up using a free command line app called Web Screen Capture. It only works on windows and I don't know how scalable it is so use at your risk.

Resources