Adding images to an HTML document with JavaScript - javascript

I've tried some HTML DOM code from several sites, but it isn't working. It isn't adding anything. Does anyone have a working example on this?
this.img = document.createElement("img");
this.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = getElementById("gamediv");
src.appendChild(this.img)
But it isn't adding anything to the div gamediv. I've tried document.body as well, with no result.

You need to use document.getElementById() in line 3.
If you try this right now in the console:
var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";
var src = document.getElementById("header");
src.appendChild(img);
<div id="header"></div>
... you'd get this:

With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As JavaScript reads down a page).
<head>
<script type="text/javascript">
function insert(){
var src = document.getElementById("gamediv");
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src.appendChild(img);
}
</script>
</head>
<body>
<div id="gamediv">
<script type="text/javascript">
insert();
</script>
</div>
</body>

This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');

Use Image() instead
Instead of using document.createElement() use new Image()
const myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement('img').

or you can just
<script>
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>

Get rid of the this statements too
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)

Things to ponder:
Use jquery
Which this is your code refering to
Isnt getElementById usually document.getElementById?
If the image is not found, are you sure your browser would tell you?

Related

How to insert <img> tag, or JS script through textContent? [duplicate]

I've tried some HTML DOM code from several sites, but it isn't working. It isn't adding anything. Does anyone have a working example on this?
this.img = document.createElement("img");
this.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = getElementById("gamediv");
src.appendChild(this.img)
But it isn't adding anything to the div gamediv. I've tried document.body as well, with no result.
You need to use document.getElementById() in line 3.
If you try this right now in the console:
var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";
var src = document.getElementById("header");
src.appendChild(img);
<div id="header"></div>
... you'd get this:
With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As JavaScript reads down a page).
<head>
<script type="text/javascript">
function insert(){
var src = document.getElementById("gamediv");
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src.appendChild(img);
}
</script>
</head>
<body>
<div id="gamediv">
<script type="text/javascript">
insert();
</script>
</div>
</body>
This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');
Use Image() instead
Instead of using document.createElement() use new Image()
const myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement('img').
or you can just
<script>
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>
Get rid of the this statements too
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)
Things to ponder:
Use jquery
Which this is your code refering to
Isnt getElementById usually document.getElementById?
If the image is not found, are you sure your browser would tell you?

Why inserting the same image object twice in html does not work?

I'm trying to insert the same image into two different divs. But the image is only displayed in the last one. It looks like the same object can only appear once in html.
var img = new Image();
img.src = '/image1.jpg';
img.onload = function(){
$('#div1').html(img);
$('#div2').html(img);
}
Only #div2 display the image.
Update to add code snippet
var img = new Image();
img.src = "http://via.placeholder.com/350x150";
img.onload = function(){
img.id = '#jcrop-target';
$('#jcrop').html(img);
img.id = '#jcrop-preview';
$('#preview').html(img);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jcrop"></div>
<div id="preview"><div>
I used this solution, but it seemed very inelegant.
var img = new Image();
img.src = 'http://via.placeholder.com/350x150';
img.onload = function(){
$('#jcrop').html('<img id="jcrop-target" src="'+img.src+'" />');
$('#preview').html('<img id="jcrop-preview" src="'+img.src+'" />');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jcrop"></div>
<div id="preview"></div>
The Image() constructor creates a new HTMLImageElement instance. It is functionality equivalent to document.createElement('img'). This creates a node in DOM tree structure complete with its dimensions and properties. It also has a specific position in the tree structure. It can't be at two different places in the tree structure. So you will have to make another element if you need, or you can try to clone it.
You can use class instead of id if you need to place image in multiple div elements.
var img = new Image();
img.src = '/image1.jpg';
img.onload = function(){
$('.div').html(img);
}
so that you can add same image in multiple div
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
There you go
var elem1 = document.createElement("img");
elem1.setAttribute("src", "http://via.placeholder.com/350x150");
var elem2 = document.createElement("img");
elem2.setAttribute("src", "http://via.placeholder.com/350x150");
document.getElementById("div1").appendChild(elem1);
document.getElementById("div2").appendChild(elem2);
<div id="div1">
</div>
<div id="div2">
</div>
Replace http://via.placeholder.com/350x150 with your source /image1.jpg

Add Links to Images in a Script

This script replaces the background of the DIV 'middle' with the images listed in the array. Currently the script works perfect but I want to be able to assign a link to each image, tried just replacing with but then the image doesn't show up nor does the link work.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg');
var nextimage=0;
doSlideshow();
function doSlideshow(){
if(nextimage>=images.length){nextimage=0;}
$('.middle')
.css('background-image','url("'+images[nextimage++]+'")')
.fadeIn(500,function(){
setTimeout(doSlideshow,5000);
});
}
</script>
What I'm looking for is something like this.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg'); To: var images=new Array('<img src="/images/home/imgone.jpg"', '<img src="/images/home/imgtwo.jpg"', '<img src="/images/home/imgthree.jpg"', '<img src="/images/home/imgfour.jpg"', '<img src="/images/home/imgfive.jpg"');
</script>
Although this does not fully answer your question, maybe you can get some ideas from DOM functions.
Example
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.body.appendChild(image);
</script>
This appends an image to the body. If you would like to add it to a specific ID, you could do the following (assuming your div id is "destination").
Example
<!DOCTYPE html>
<html>
<body>
<div id="destination">
<!-- Destination Div -->
</div>
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.getElementById("destination").appendChild(image);
</script>
</body>
</html>
Good luck!

Adding an img element to a div with javascript

I am trying to add an img to the placehere div using JavaScript, however I am having no luck. Can anyone give me a hand with my code?
<html>
<script type="text/javascript">
var elem = document.createElement("img");
elem.setAttribute("src", "images/hydrangeas.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild("elem");
</script>
<body>
<div id="placehere">
</div>
</body>
</html>
document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';
It should be:
document.getElementById("placehere").appendChild(elem);
And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:
window.onload = function() {
var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
<div id="placehere"></div>
To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.
function image()
{
//dynamically add an image and set its attribute
var img=document.createElement("img");
img.src="p1.jpg"
img.id="picture"
var foo = document.getElementById("fooBar");
foo.appendChild(img);
}
<span id="fooBar"> </span>
The following solution seems to be a much shorter version for that:
<div id="imageDiv"></div>
In Javascript:
document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';
In case anyone is wondering how to do it with JQuery:
$("<img height='200' width='200' alt='testImage' src='https://avatars.githubusercontent.com/u/47340995?v=4'> </img>").appendTo("#container");
Ref: https://api.jquery.com/jQuery/#jQuery2

Javascript will not load the pictures

I want to load these banner.png files to the screen but all it prints out is the actual text from the banner array?
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}
any thoughts? I think I need to some how add a src but I am not sure how.
Might be too obvious, but...
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return '<img src="' + banner[randNum] + '" />';
}
Demo: http://jsfiddle.net/AlienWebguy/u7yfq/
My pure javascript DOM manipulation is a little fuzzy (usually use jquery) but something like this should do the trick:
<div id="images"></div>
<script type="text/javascript">
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
var container = document.getElementById('images');
var img = document.createElement('img');
img.setAttribute('src',banner[randNum]);
container.appendChild(img);
}
</script>
The instruction that loads the image should be like this.
Where imgElement is an IMG element.
imgElement.src = randImg();
If you don’t know how to get an IMG element. Give the IMG element an ID attribute and load this like this.
For an IMG element as <img id="myImage" src="" />
Then:
var imgElement = document.getElementById("myImage");
imgElement.src = randImg();
Note.- my answer gives instruction on how to change the source of an IMG element that exists in the DOM (It is recommended to do so). You should NEVER document.write() an element, Neither on demand or when page is loading. That practice has been deprecated and many browsers would delete the whole page contents if you do so.

Categories