JavaScript inserting images using string variable as their URL - javascript

I'm using JavaScript to parse a XML file. One of the XML's attribute is an URL which links to an image. eg. http://localhost/pic.jpg
As the parsing goes on, I use an variable to hold each URL(which is a string variable) and hoping that I can show these images in a table.
The following is part of my code:
for(i = 0; i < row.length; i++)
{
// looping through the XML file
var Logo1 = row[i].getElementsByTagName("Logo")[0].childNodes[0].nodeValue;
//Logo1 is the string which is a URL
document.write("<img src= 'Logo1' width='256' height='128'>");
}
I use Chrome, but the images won't load....
enter image description here
Can someone help?

If Logo1 is a variable containing an image path (URL, as you say), you need to build the img tag in a way that includes the path:
document.write('<img src="' + Logo1 + '" width="256" height="128">');
This concatenates the Logo1 string variable into the rest of the tag.
That said, document.write is probably not going to work for you in the long run. you would instead create a new Image object and set its src property:
var testImage = new Image();
testImage.src = Logo1;
// add testImage to the DOM

Related

How to find image tags in a string in node js

I have a string with image tags like below
var str = '<img src="www.client.jpg><img src="www.custums.png">';
I have to find the image tags and src i.e I need to push the image tags into an array but right now I cannot use jsdom since I had a version problem right now in my server.So, can anyone please suggest me help to do this with not using jsdom.Thanks.
Just split the string and then filter to the urls like so;
var str = '<img src="www.client.jpg"><img src="www.custums.png">';
console.log(str.split("\"").filter(t => t.startsWith("www.")));
Your example was missing a ", it would make it so this doesn't parse correctly, but assuming the html is actually of that form but without errors it will give you just the urls.
you can use xpath to extract, the path would be //img#src. alternatively, you can use an xml to json parser ; sth like fast-xml-parser
Split the string into an array of image tag. Convert strings into HTML DOM objects as shown below. Then you can easily get the src of image tag.
var str = "<img src='www.client.jpg'><img src='www.custums.png'>";
var newstring = str.replace(/></gi, ">,<"); // Replace '><' with '>,<' so that you can split with ','
var imgs = newstring.split(",");
for(i=0; i<imgs.length; i++) {
// Create a temporary div, assign img string as its innerHTML, then gets its content
var d = document.createElement('div');
d.innerHTML = imgs[i];
// Reassign the imgs array with HTML DOM object instead of string
imgs[i] = d.firstChild;
console.log(imgs[i].src);
}

Node.src = variableName/adding HTML image with innerHTML and variable issue

I'm trying to incorporate some images "dynamically" by saving them as variables in an array and then editing the innerHtml of some divs to include them, but the images aren't showing. I'm using img.src = varName; Here's a link to the code: https://repl.it/GBoa/1 (here's also a link to a website version where the images were uploaded: cardtestwdi.bitballoon.com). I would appreciate any help I could get.
If you want to set innerHTML using a string, you will have to provide the full HTML string. You can't create a string and then use properties for regular DOM nodes. For example, you could use the following:
var imgElement = "<img src='" + myArray[i] + "' alt='test' width='200px' height='275px'/>";
However instead of doing this I would recommend creating the node in JavaScript using document.createElement and append it to the DOM using document.appendChild:
var imgElement = document.createElement('img');
imgElement.width = 200;
imgElement.height = 275;
imgElement.src = myArray[i];
myCard[i].appendChild(imgElement); // Append the image node to the card node

Javascript/HTML HREF created with Variables Doesnt Work with Spaces

I'm using JavaScript in HTML to create an HREF link from a couple of variables.
The first variable is the fixed text for the start of an Android file path (the same every time) and the second variable is the file name which is taken from an XML attribute.
It's all works nicely, BUT it only constructs the link properly if I DO NOT have any spaces in the file name variable from the XML document.
Basically what's happening is if the file name variable contains a space, it only constructs the link up until the first space in the file name so an example would be
**Correct link =**
example file name.pdf
**Link my code incorrectly returns =**
example file name.pdf
Help would be greatly appreciated.
Thanks!
<script>
xmlDoc=loadXMLDoc("PBFileNames.xml");
x=xmlDoc.getElementsByTagName("file");
var path = "file:///sdcard/Clients/PB/"; //this will be constant between all iterations
for (i=0;i<x.length;i++)
{
var filename = x[i].getAttributeNode("name").nodeValue; //the nodefile is the filename
{
document.write("<br>");
document.write("" + filename + "");
document.write("<br>");
}
}
</script>
You have to escape the URI
document.write("" + filename + "");

How to add an object to a html string?

I'm trying to load several images by a drop action and than resizing them and adding them as a thumbnail. The resize part is very important because the images can be very large and I want to make the thumbnails small of size.
Here is my code:
loadingGif(drop);
for (var i=0;i<files.length;i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = function(e) {
var src = e.target.result;
var img = document.createElement('img');
img.src = src;
var scale = 100/img.height;
img.height = 100;
img.width = scale*img.width;
output.push('<div id="imagecontainer"><div id="image">'+img+'</div><div id="delimage"><img src="img/del.jpg"" /></div></div>');
if(output.length == files.length) {
drop.removeChild(drop.lastChild);
drop.innerHTML += output.join('');
output.length = 0;
}
}
reader.readAsDataURL(file);
}
As you can probably tell I insert a loading gif image in my dropzone until all files are loaded (output.length == files.length). When a file is loaded I add html to an array which I will print if the load is complete. The problem is I can't seem to add the img object (I need this object to resize the image) to the html string, which seems obvious as the img is an object... So my question to you guys is: how do I do this? :)
Generally speaking, it's bad habit to play with DOM elements as strings. You should instead use the native javascript (or the library/framework you are using) commands to create the elements and set their attributes.
For example if you have an element with id "image-container" which contains all your images, you may write.
var container = document.getElementById( 'image-container' );
var img = document.createElement( 'img' );
container.appendChild( img );
Instead of a large HTML string containing all your output, you can then have only a reference to an element containing all the other elements, and either appending it to the body as soon as all the elements have been loaded, or keeping it hidden and showing it when the loading is complete.
if (output.length == files.length) {
drop.removeChild(drop.lastChild);
drop.appendChild( container );
output.length = 0;
}
Remember IDs have to be unique. There cannot be more than one element with the same ID in the same document.
HTML is parsed into elements when inserted onto the page, but that doesn't mean the two formats 1 to 1 translatable.
You could use outerHTML to translate the <img> element to a HTML string. But this wont be efficient. You are translating an element to a string only to be parsed as an element again. Kinda sloppy.
"<div id='image'>"+ img.outerHTML +"</div>"
You could build the <img> tag as a string.
"<div id='image'><img src='"+ src +"'></div>"
But that starts to get hairy too. So lastly you could append the image element after you create the other html.
drop.innerHTML = "<div class='image'></div>"
document.querySelectorAll('.image:last-child')[0].appendChild(img);
However, food for thought: when you start having this much HTML in your JS, you may want to rethink your approach a bit. It's a hard to maintain and very human error prone pattern.
As others have said, there are reasons why one would avoid/choose to use strings to represent DOM elements. Also, it's a bit of a wtf moment reading code that attempts to mix both methods of representing html elements. that said, you can skip creating the image as an element in and of itself, instead inserting the appropriate string into your result(stack?).
This would have the desired scaling effect:
var src = e.target.result;
var imgStr = "<img src='" + src + "' height='" + 100 + "'/>";
ouput.push('<div id="imagecontainer"><div id="image">'+imgStr+'</div><div id="delimage"><img src="img/del.jpg"" /></div></div>');
You can create an object with arbitrary properties, in order to hold both the image and your HTML string:
var result = {
html: '<div id="imagecontainer"><div id="image">'+img+'</div><div id="delimage"><img src="img/del.jpg"" /></div></div>',
imgTag: img
}
output.push(result);
And then later on when you iterate through the results array, you can access these parts as result.html or result.imgTag (changing the first part to whatever variable you've assigned the object to).
It does mean that you'd need to change your current output.join('') to a loop that actually iterates through the values of output and concatenates their html properties instead. If you really wanted to avoid this, you could stick the images in a separate output-style array. But this isn't as clean, and runs the risk of the two array contents becoming out-of-sync. I'd stick to having two separate properties of the same object, as cleaner and better.

jquery append does not work for duplicate image object refernce

I have an 10 images,
each image represents digit 0-9 in a special font (thus the images)
in order to improve performance and delay, i pre-loaded the following images like the following:
function createDigit() {
for (var i = 0; i < 10; i++) {
var obj = new Image;
obj.src = 'digit' + i + '.png';
digitHash[i] = obj;
}
}
so in digit hash, i have keys indexed from 0 to 9, and each corresponding value is the image object reference, which src is mapped to the image file location.
now in my html, i have a div tag
<div id='digits'></div>
now say i want to display '2000'
so i have the following jquery
$('#digits').append(dightHash[2], dightHash[0], dightHash[0], dightHash[0]);
it only displays '20'
After some debugging and printing in firefox console, i notice that it happens when you are appending the SAME image reference more than once!
in other words, the second zero and third zero in '2000' are not appended and thus we only have '20'
if i append the following:
$('#digits').append(dightHash[2], dightHash[3], dightHash[4], dightHash[5]);
i get the full display of '2345', becauase there is no duplicate image reference in append
How can I resolve this issue?
is there any other than append method of jquery i can use??
Thanks
As had already been explained, .append() moves an object from wherever it is to the specified location. It does not make a copy of the object.
Because of that, I would suggest you just create the desired objects like this and then you don't have to worry about duplicate digits as they will each get their own image object this way:
// create an individual image
function makeDigit(n) {
var img = new Image();
img.src = 'digit' + n + '.png';
return(img);
}
// Force all images into browser memory cache for fast loading:
function cacheDigits() {
for (var i = 0; i < 10; i++) {
digitHash.push(makeDigit(i));
}
}
$('#digits').append(makeDigit(2), makeDigit(0), makeDigit(0), makeDigit(0));
Yes, append actually move around your DOM, instead of automatically making copies of the object you are appending.
You can call .clone() so that appends take the copy of your image and append it instead of moving around the ref
$('#digits').append(dightHash[2], $(dightHash[0]).clone(), $(dightHash[0]).clone(), $(dightHash[0]).clone());

Categories

Resources