load an image in a particular element using javascript - javascript

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.

Related

Displaying images with given URL in a json string on a html page

I am working on a project where I call a certain API and in response I get back a json string with all the information. I need to find a way using javascript to display this json string into a table format. I got a very basic version of this running. However, the problem I am having is that I cannot find a way to display a image in this block of code.
results.html file:
<!DOCTYPE HTML>
<html>
<head>
<title>
How to convert JSON data to a
html table using JavaScript ?
</title>
<h1>Results: </h1>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style = "text-align:center;" id = "body">
<h3>Showing resuls for: {{searchQuery}}</h3>
<p>{{responseText}}</p>
<br><br>
<table align = "center"
id="table" border="1">
</table>
<div id="header"></div>
<script>
var el_up = document.getElementById("GFG_UP");
var list = [];
list = "{{responseText|escapejs}}";
//console.log(list);
var titles = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 't' && list[i+1] == 'i')
{
var title = '';
for(var j = (i+8); list[j] != ","; j++) {
title += list[j];
}
i = j;
console.log(title + ", ")
titles.push(title)
}
}
console.log(titles)
var images = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 'h' && list[i+1] == 't')
{
var image = '';
for(var j = (i); list[j] != ","; j++) {
image += list[j];
}
i = j;
console.log(image + ", ");
var img = new Image();
img.src = image.slice(0, -1);
images.push(img);
}
}
console.log(images)
var restaurants = []
for (var i = 0; i < list.length-17; i++) {
if(list[i] == 'r' && list[i+1] == 'e' && list[i+2] == 's')
{
var restaurant = '';
for(var j = (i+17); list[j] != ","; j++) {
restaurant += list[j];
}
i = j;
console.log(restaurant + ", ")
restaurants.push(restaurant)
}
}
console.log(restaurants)
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
console.log(typeof(cellData))
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
})
table.appendChild(tableBody);
document.body.appendChild(table);
};
var a = [titles, restaurants, images]
console.log(a)
createTable(a);
</script>
</body>
</html>
The function createTable is the one in question. It displays the text parts correctly. Im not sure how to get it to display images given the URLs of those images in a table.
output HTML file:
HTML output
You should show us the API response you are working with here.
Another thing is your createTable function expects to get table data. But onclick on your button pass there #table ID. Not sure if it should be like this.
Also you could run your JS script when all page is loaded:
window.onload = () => {
// Your JS script which should do something after page is loaded.
}
Finally it comes to the images. I think that you are not using img tag anywhere so your images simply won't be visible in the table. If you would like to see them just create img element and put it into td.
Few advices (not related with your question):
stop using console.log so much, place debugger statement in your code and debug it like a pro, if you don't know how just look for it in youtube,
please put your attention to a code style, it is a bit messy, if you have real trouble with it use ESlint to fix it for you.
EDIT
About images - if you want to create DOM element for img use code below instead of current one:
var img = document.createElement("IMG");
Than you can set src and other things like alt and so on:
img.src = imgUrlString;

How to get attribute ID to parameter of function js

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");

Modal doesn't work

I made a modal using jQuery, but it doesn't seem to work properly. I'm calling my images in a javascript function, and the modal is in my window.onload in the same page the images are loaded. I'm loading the images first, but the modal only works if i put the imgs directly in the HTML and if i take everything else from the window.onload. That's how i'm calling all imgs:
function maisGaleria(n){
var galeria = new Array();
var img = document.querySelector("#gallery");
var pic = 0;
if(n == 1){
pic = 4;
}else if(n == 2){
pic = 7;
}else{
pic = 4;
}
img.innerHTML = "<div class='row'>";
img.innerHTML += "<div class='six columns'>";
img.innerHTML += "<h4>Galeria "+n+"</h4>";
for(var i = 0; i < pic; i++){
galeria[i] = "foto"+n+"_"+(i+1)+".jpg";
}
for(var i = 0; i < galeria.length; i++){
img.innerHTML += "<img src='img/"+galeria[i]+"' class='imgs-modal'>";
}
img.innerHTML += "</div>";
img.innerHTML += "</div>";
}
and the window.onload with the modal:
window.onload = function(){
var rdSocial = document.querySelector("#social");
var teste = document.querySelector("#teste");
var fb = '<img src="img/fb.png" value="1" class="img" onclick="redireciona(this);">';
var twt = '<img src="img/twitter.png" value="2" class="img" onclick="redireciona(this);">';
var insta = '<img src="img/insta.png" value="3" class="img" onclick="redireciona(this);">';
rdSocial.innerHTML += fb;
rdSocial.innerHTML += twt;
rdSocial.innerHTML += insta;
var x = location.search.split("?gal=")[1];
y = document.querySelector("#pics");
//console.log(x);
y.onload = maisGaleria(x);
//the modal starts here
$('.imgs-modal').on('click', function(){
var obj = $(this).clone();
console.log(obj);
$("#box_modal").html(obj);
$("#modal").fadeIn(1000);
});
$(".fechar").on('click', function(){
$("#modal").fadeOut(1000);
});
}
#anuseranother there are few errors in you code.
Before calling maisGaleria method in window.onload, you have to declare/define it.
As per your jsfiddle, it is throwing errors like maisGaleria is not defined. So define maisGaleria it before using it.
After fixing this error, another error is "Cannot set property 'onload' of null". There is no #pics element in the dom (y = document.querySelector("#pics")) and you are referencing it and adding onload method to it. Please update these two and let us know exactly how you need a modal with images any example in internet.

Javascript - Add images

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) );
}
}());

javascript appenchild

for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}

Categories