I have some images (image1, image2, image3 ..etc. ) and I will add those images to each cell seperately. I found a code to insert the images.
document.getElementById("cell1").innerHTML = "<img src='image1.png'>";
Now, Can someone help me to put above code in a loop in order to avoid to write same code for each image ?
I have tried below code but it does not work. Probably there is a problem with quotes. Or is there a better way to insert multiple images to each cells ?
for (x=0; x=10; x++) {
document.getElementById("'cell" + x + "'").innerHTML = "<img src=" + "' + x + ".png'>"; }
for (x=0; x=10; x++) {
document.getElementById("cell" + x).innerHTML = "<img src='image" + x + ".png' />";
}
for (x=0; x=10; x++) {
var img = new Image();
img.src = 'image' + x + '.png';
document.getElementById('cell' + x).appendChild(img);
}
As you may have noticed creating elements from html strings can get really messy really quick.
Its often a a better idea to use document.createElement to create the elements and then manipulate the properties of the element.
img = document.createElement("img");
img.src = "image" + i + ".png"; // image1.png ... etc
Another very useful technique is using document fragments to create ad-hoc collections of elements before we actually attach them to the real document or elements.
frag = document.createDocumentFragment();
frag.appendChild(img);
targetNode.appendChild(fragment); // attach all the images in the fragment
This is good for performance since actually touching the DOM is slow - we don't want to do it over and over in a loop.
Lets take these two techniques and create a function which creates img elements
function createImages(n){
var i, frag, img;
frag = document.createDocumentFragment();
for (i = 0; i < n; i ++) {
img = document.createElement("img");
img.src = "image" + i + ".png"; // image1.png ... etc
frag.appendChild(img);
}
return frag;
}
We could use this function to attach images to each cell in table
var table = document.getElementById('test'),
cells = table.getElementsByTagName('td');
(function(){
var i,
len = cells.length,
images = createImages(3);
for (i = 0; i < len; i++) {
cells[i].appendChild( images.cloneNode(true) );
}
}());
Related
I need put 5 images on page like thumbnail, and after click show the lightbox. I need put ID of element what I create to function like parameter. But i cant get ID. I was looking for this problem here and with google but nothings work :( It is project to school and I can use only html, css and javascript, I can not use jquery. Thanks. Here is my code:
function onloadpg() {
for (var i = 0; i<5; i++) {
x[i] = document.createElement("IMG");
x[i].setAttribute("src", "images/" + (i+1) + ".jpg");
x[i].setAttribute("width", "250");
x[i].setAttribute("height", "200");
x[i].setAttribute("alt", fotky.title);
x[i].setAttribute("title", fotky.title);
x[i].setAttribute("id", i+1);
x.setAttribute("onclick", zobraz(x.getAttribute('id')), nacitaj(x.getAttribute('id')));
}
Problem :
You could see in the browser console the message :
Uncaught TypeError: x.setAttribute is not a function
Solution :
You need to use x[i] instead of x to target the current element by index in :
x.setAttribute("onclick", zobraz(x.getAttribute('id')), nacitaj(x.getAttribute('id')));
^________________________________^______________________________^
Should be :
x[i].setAttribute("onclick", "zobraz("+x[i].getAttribute('id')+")", "nacitaj("+x[i].getAttribute('id')+")");
^^^^_________________________^_______^^^^^^___________________^^^^___________^^^^^^___________________^^^^^
Note also that you've to add quotes " and concate variables.
NOTE : You should define the variable x as array :
var x = [];
Hope this helps.
function onloadpg() {
var x = [];
for (var i = 0; i < 5; i++) {
x[i] = document.createElement("IMG");
x[i].setAttribute("src", "images/" + (i + 1) + ".jpg");
x[i].setAttribute("width", "250");
x[i].setAttribute("height", "200");
x[i].setAttribute("alt", "fotky.title");
x[i].setAttribute("title", "fotky.title");
x[i].setAttribute("id", i + 1);
x[i].setAttribute("onclick", "zobraz("+x[i].getAttribute('id')+")", "nacitaj("+x[i].getAttribute('id')+")");
document.body.innerHTML += x[i].outerHTML+"<br>";
}
}
function zobraz(id) {
alert('zobraz : '+id);
}
function nacitaj(id) {
alert("nacitaj : "+id);
}
onloadpg();
function onloadpg(element_id) {
var elem = document.getElementById(element_id);
for (var i = 0; i<5; i++) {
x[i] = document.createElement("IMG");
x[i].setAttribute("src", "images/" + (i+1) + ".jpg");
x[i].setAttribute("width", "250");
x[i].setAttribute("height", "200");
x[i].setAttribute("alt", fotky.title);
x[i].setAttribute("title", fotky.title);
x[i].setAttribute("id", i+1);
x.setAttribute("onclick", zobraz(x.getAttribute('id')),nacitaj(x.getAttribute('id')));
}
onloadpg("element_id");
I have an array of image variables that get preloaded using javascript to make an image sequence animation. The issue I have is setting the img element from HTML to use one of these images. It seems all the properies are strings?
Here's how I set the array of images in javascript:
for(var i = 0; i < 30; i ++){
anim[i] = new Image();
if(i < 10){
anim[i].src = "images/anim/frame0" + i + ".png";
}
if(i >= 10){
anim[i].src = "images/anim/frame" + i + ".png";
}
}
and I simply have an
^img tag = "animation"^
in html that I want to change.
Your code looks valid.
for(var i = 0; i < 30; i++){
anim[i] = new Image();
if(i < 10){
anim[i].src = `images/anim/frame0${i}.png`;
}
if(i >= 10){
anim[i].src = `images/anim/frame${i}.png`;
}
}
Now you can do:
document.body.appendChild(anim[0]);
I tested this and it works for me.
If you want to change src on the fly then you'd have to select the appended element and update its src like this: document.querySelectorAll('img')[0].src = newSourceVariable;.
I have a place for the main photo (id = "main") and other photos in the table (id = "pic+1(2,3,4,5,6)"). I would like to click on a photo with id = "pic n" and to load it in the element with id "main". How to realize this?
Also I have an error
Uncaught TypeError: Cannot set property 'onclick' of null.
Here is my code:
<img id="main" src="">
galery(dir){
...
...
function createPreview() {
var f = document.createElement("table");
var row = f.insertRow();
for(var j = 0; j < count ; j++) {
var cell = row.insertCell(j);
var img = new Image();
img.src = dir + '/' + j + ".jpg";
img.width = "100";
img.id = 'pic' + j;
cell.appendChild(img);
}
document.body.appendChild(f);
}
document.getElementById(this.pic).onclick = function() {
document.getElementById('main').src = this.src;
}
...
}
Although your code has many errors and misunderstandings on how js works here is some simple code that solves this issue
//fake an image directory
var count = 3;
var dir = 'http://lorempixel.com/300/300/abstract/'
//setup a table
var f = document.createElement("table");
var row = f.insertRow();
for (var j = 0; j < count; j++) {
var cell = row.insertCell(j);
imagepath = dir + j;
cell.innerHTML = '<img src="' + imagepath + '" width="100" onclick="showmain(' + j + ')">';
}
document.body.appendChild(f);
//change imagesrc in main tag
function showmain(image) {
document.getElementById('main').src = dir + image;
}
This is the most basic (noob) thing you do with javascript.
I strongly suggest you read some more tutorials before coming back with such basic questions.
Here is a Plunker.
No onload handler, so the script is at the end of the page.
You have a lot of errors in your code:
1) You define var f inside the function, so its scope is inside the function. But then you try to get it outside the function with document.body.appendChild(f); which doesn't work. you should move document.body.appendChild(f); inside the function.
2) Then you get Uncaught TypeError: Cannot set property 'onclick' of null. because document.getElementById(this.pic) returns null. this.pic returns no id.
3) close your img tag.
4) You have 2 extra }
And I am sure there are more if you show us all your code.
I'm trying to use JavaScript to list images 01-40 in order automatically.
Like this:
<img src="01.jpg" />
<img src="02.jpg" />
<img src="03.jpg" />
<img src="04.jpg" />
<img src="05.jpg" />
...
I don't want to write each img src manually, as I want to use this on multiple pages
I'd like the image starting and ending number to be variables that I can edit easily.
You need the parent element for imgs:
for ( var i = FIRST_NUMBER ; i < LAST_NUMBER ; i++ ) {
var elem = document.createElement("img");
if ( i < 10 ) {
elem.setAttribute("src", "0"+i+".jpg");
} else {
elem.setAttribute("src", i+".jpg");
}
document.getElementById(PARENT_ID).appendChild(elem);
}
function img_create(startIndex, endIndex) {
for (i = startIndex; i <= endIndex; i++) {
var oImg=document.createElement("img");
oImg.setAttribute('src', i+".jpg");
//other attributes you need
document.body.appendChild(oImg);
}
}
Working example: http://jsfiddle.net/Lw3bjcx4/1/
function createImages(count, elementId) {
// Get the container element where you want to create the images
var element = document.getElementById(elementId)
// Loop count times over to create count image elements
for (var i = 0 ; i < count ; i++) {
// Create a new image element
var imageElement = document.createElement('img')
// Set the source to index.jpg where index is 0,1,2,3.... count
imageElement.setAttribute('src', i + ".jpg")
// Append the new image element to the choosen container.
element.appendChild(imageElement)
}
}
// Test to create 10 images.
createImages(10,"imgs")
You can use like this:
var imgdiv = document.getElementById('imgdiv');
var img = imgdiv.getElementsByTagName('img');
for(var i=0;i<40;i++){
img[i].src=i+'.jpg';
}
Here is an alternative to all other answers, where you don't need to use an id to put images in. Just paste the script tag where you need to have the images. For example, if you put it in a div, the script will automatically insert the images in place.
<script type="text/javascript">
var thisScriptNode = document.currentScript;
for(var i = 1 ; i <= 40 ; i++) {
var img = document.createElement("img");
img.src = ("00" + i).substr(-2) + ".jpg";
thisScriptNode.parentNode.insertBefore(img, thisScriptNode);
}
</script>
You can easily change the number of leading zeros. For example, to get numbers with three characters, replace "00" with "000" and -2 with -3.
var to = 10;
var from = 0;
for (i = from; i < to; i++){
var elem = new Element('img', { src: i + '.jpg' });
document.body.appendChild(elem);
}
it will append to <body> images with names from 0.jpg to 9.jpg
I want to alter the following Java script to make it more efficient
for(var i = 0; i < 1000; i += 1){
var el = document.createElement('div');
el.appendChild(document.createTextNode('Node ' + (i + 1)));
document.getElementById('nodeHolder').appendChild(el);
}
Ideally it would be grateful if the reason behind it could be provided.
Any idea would be very much appreciated.
Create a document fragment and append to that, then do a single append for the entire set.
var frag = document.createDocumentFragment();
for(var i = 0; i < 1000; i += 1){
var el = document.createElement('div');
el.appendChild(document.createTextNode('Node ' + (i + 1)));
frag.appendChild(el);
}
document.getElementById('nodeHolder').appendChild( frag );
Now your getElementById only needs to run once, and the DOM only needs to update once.
The document fragment is a generic container. When appending it to the DOM, the container just disappears, and only its content is appended.
You can condense the code a bit if you like:
Example: http://jsfiddle.net/7hagb/
var frag = document.createDocumentFragment();
for(var i = 0; i < 1000; i += 1){
frag.appendChild(document.createElement('div'))
.appendChild(document.createTextNode('Node ' + (i + 1)));
}
document.getElementById('nodeHolder').appendChild( frag );
Additionally, a very minor optimization would be to get rid of the i + 1, and modify the for loop to provide the values you want.
Example: http://jsfiddle.net/7hagb/1/
var frag = document.createDocumentFragment();
for(var i = 1; i <= 1000; i += 1){
frag.appendChild(document.createElement('div'))
.appendChild(document.createTextNode('Node ' + i));
}
document.getElementById('nodeHolder').appendChild( frag );
You can use DocumentFragment, a lightweight node container which prevents DOM from refreshing and reflowing when you append nodes on it.
var nodeHolder = document.createElement('div'),
fragment = document.createDocumentFragment();
for (var i = 0; i < 1000; i ++ ) {
var el = document.createElement('div');
el.innerHTML = 'Node ' + (i + 1);
fragment.appendChild(el);
}
nodeHolder.appendChild(fragment);
do not use DOM, just use html instead.
for example instead of createElement use
abc = ""
for(...){
abc += "<div>Text " + i + "</div>";
}
and then append to the target.
It is ugly, I agree, but should run much faster