I have a pattern for the names of the images. The second part (in the script below it is "whatever") will be used as additional information. This part is A-z. How can I load images with such names?
var createdImg = document.createElement('img');
createdImg.setAttribute('src','firstPart_' + whatever + '_.jpg');
Just add the element to the DOM. If you are using jquery, you can do something like this:
var whatever = 'test';
$("body").append("<img src='"+ 'firstPart_' + whatever + '_.jpg' +"'>");
here is the bin
Related
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
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
I would like to create an HTML image element like this one:
<img src="www.example.com?param1=aid¶m2=sid¶m3=user¶m4=now" />
I tried doing this:
var now = new Date().getTime();
var aid = 123456;
var sid = 78910;
var user = "abcd";
How can I create the element from this data?
You create an img element (not "tag") using document.createElement('img').
You set its src, a string, using the src reflected property of that element. To create that string, for now, you'd use string concatenation (+). See below for an ES6 note, however.
So:
var img = document.createElement('img');
img.src = "www.example.com?param1=" + aid +
"¶m2=" + sid +
"¶m3 = " + encodeURIComponent(user) +
"¶m4=" + now;
Then you'd want to append that to the DOM somewhere.
Note the encodeURIComponent on the non-numeric one. Both the names and values in a query string must be URI-encoded. But I haven't bothered on param1, param2, etc. because I know that the URI-encoded version of them is...exactly the same. Similarly I know that the URI-encoded version of a number is just the number. But I see user is a text value, and I assume it isn't always "abcd", so to guard against issues I've URI-encoded it.
Re your comment:
And presumably if I'd like to add attributes to the img element it'd be like img.height=1 and img.width=1?
The specification lists the properties of img elements. Yes, both height and width are there and setting them has the same effect as using the height and width attributes, although you might want to use a stylesheet instead.
Not all attributes have reflected properties. For those that don't, you'd use setAttribute("name", value) (the value will be converted to a string if it isn't already one).
As of the next version of JavaScript, ECMAScript6 (ES6), you'd be able to use a template string for src instead:
var img = document.createElement('img');
img.src = `www.example.com?param1=${aid}¶m2=${sid}¶m3=${encodeURIComponent(user)}¶m4=${now}`;
Strings in JS can be chained together with the + operator. Number values will be coerced to strings (although that sometimes won't work as expected).
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.
I'm using JavaScript to copy a specific div from a page into a new page. I need to remove the ID attributes for each table in the new page.
It seems that since I'm copying content from the first page, I can filter out the IDs from the string before it is written to the second page. Can jQuery take a variable as its 'focus'? Instead of manipulating the entire DOM, manipulate a particular string?
I have a non-working version of what I'm talking about:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
$("table", htmlToCopy).removeAttr('id');
currentContent.document.open();
currentContent.document.write(htmlToCopy);
currentContent.document.close();
You need to create a jQuery object by calling $(html), manipulate it, then get the HTML back by calling html().
For example:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
var newStructure = $("<div>" + htmlToCopy + "</div>");
newStructure.find("table").removeAttr('id');
currentContent.document.open();
currentContent.document.write(newElements.html());
The <div> element allows me to get its inner HTML and get the HTML you're looking for.
Who not just remove ID= as a string and forget DOM manipulation all together?
First make the string a jQuery object, then work with it:
htmlToCopy = $(htmlToCopy).find("table").removeAttr('id').end().html();