JavaScript images - javascript

How do I display the same image on the same page multiple times?
<head>
<Script language="javascript">
function xdf(){
for (i=0;i<10;i++) {
document.write('<b>hello world</b><br>');
}
}
</script>
</head>
this code displays "hello world" 10 times.
i would like the same thing but with certain image instead of "hello word"...

You can use document.createElement() to create an img element in JavaScript, and Node.appendChild() to append it to some other node:
var img = document.createElement('img');
img.setAttribute('src', 'my_image.png');
document.getElemenetById('some-div').appendChild(img);
The image will be loaded from the browser's cache if the above is repeated multiple times, appending each new img element to multiple nodes.
As #Matthew Flaschen suggested in a comment below, you could also use the Node.cloneNode() solution instead. You can create your img elment once:
var img = document.createElement('img');
img.setAttribute('src', 'my_image.png');
... and then use img.cloneNode(false) as an argument for appendChild():
document.getElemenetById('some-div').appendChild(img.cloneNode(false));
document.getElemenetById('some-other-div').appendChild(img.cloneNode(false));

<img src="/path/to/img.png"/> <img src="/path/to/img.png"/>

you can clone the images:
<div><img src="http://www.google.com/favicon.ico" id="image" /></div>
<script type="text/javascript">
n = 5;
img = document.getElementById("image");
for (i=0; i<n-1; i++) {
img2 = img.cloneNode(false);
img2.id = img.id + "_clone" + i;
img.parentNode.appendChild(img2);
}
</script>

.. or maybe you'd rather want to define the background, using CSS?
<style type="text/css">
body { background: url("http://www.google.com/favicon.ico") left repeat-y; }
</style>
(assuming from your previous comment, that you want to have the images in one column on the left edge)

Change:
document.write('<b>hello world</b><br>');
Into:
document.write('<img src="IMAGE FILE NAME HERE.png" alt="TEXT HERE"><br>');

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?

Will images not load with the page if the image tags are written with javascript and require user input?

I wanted a way to load images only when needed but am hesitant to use AJAX. Instead, will something like this work?
<div onclick="loadimages()">Section Title</div>
<script type="text/javascript">
function loadimages()
{
document.write('<img src="images/thumbnail1.jpg" />');
document.write('<img src="images/thumbnail2.jpg" />');
document.write('<img src="images/thumbnail3.jpg" />');
}
</script>
The intent is for the images to appear below the "Section Title" when that div is clicked, and for the images to be loaded only at that time.
If you want to add elements to the DOM dynamically there are several choices much more preferable than the abhorrent document.write. For example, you can do this:
var image = document.createElement("img");
image.src = "images/thumbnail1.jpg";
var parent = document.getElementById("foo"); // identify the parent somehow
parent.appendChild(image);
Or you could do this:
var parent = document.getElementById("foo"); // identify the parent somehow
parent.innerHTML += '<img src="..." />';
Or, if you use jQuery:
$("your selector here").append('<img src="..." />');
Edit: Untested code -- typed on the fly.
document.write won't do what you want after the page has loaded, you'd have to do something with the DOM..
Like, perhaps:
<div id='section_title' onclick="loadimages()">Section Title</div>
<script type="text/javascript">
function loadimages()
{
var pics = ['thumbnail1.jpg', 'thumbnail2.jpg', 'thumbnail3.jpg'];
var i, img, el;
el = document.getElementById('section_title');
for (i = 0; i < pics.length; i++) {
img = document.createElement("img");
img.src = pics[i];
el.appendChild(div);
}
}
</script>
Another way would be to put the images in your HTML file, but with display:none to hide them and unhide as needed.
Or, depending on the purpose, put them in the HTML as normal, then hide them on load and unhide then when needed.
When you do document.write('something');
This something will replace entire contents of your document.
What you can do is, create new elements dynamically and append them at appropriate places.

How can i return img.src by clicking on an image with javascript?

I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:
var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src
to call the results i have been trying to insert the image.src into my html using
document.getElementById("x").innerHTML=imageurl;
Im having very little success. Any help would be greatly appreciated. Thank you.
I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.
http://jsfiddle.net/JbHdP/
var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
if (e.srcElement.tagName == 'IMG') alert(e.srcElement.src);
};​
I think you want something like this: http://jsfiddle.net/dLAkL/
See code here:
HTML:
<div id="urldiv">KEINE URL</div>
<div>
<img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
<img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>​
JAVASCRIPT
picurl = function(imgtag) {
document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}​
Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:
alert(document.getElementById('x').src);
would spit out the src of the image.
Here's a naïve solution with just javascript (probably not cross-browser compatible):
<!doctype html>
<html>
<head>
<script>
function init() {
var images = document.getElementsByTagName('img');
for(var i = 0, len = images.length; i < len; i++) {
images[i].addEventListener('click', showImageSrc);
}
}
function showImageSrc(e) {
alert(e.target.src);
}
</script>
</head>
<body onload="init()">
<img src="http://placekitten.com/300/300">
</body>
</html>

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

Replace images in a DIV using JavaScript

I want to show different images in a DIV, the turn of an image depend on a random number.
The image name is like 1.gif, 2.gif, .. 6.gif
to do that I coded
var img = document.createElement("IMG");
img.src = "images/1.gif";
document.getElementById('imgDiv').appendChild(img);
but it does not replace the old image how ever it add an another image right in the bottom of first image.
syntax for DIV is:
<div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>
may u halp me ?
var img = document.createElement("IMG");
img.src = "images/1.gif";
var oldImg = document.getElementById('oldImg');
document.getElementById('imgDiv').replaceChild(img, oldImg);
var dv = document.getElementById('imgDiv');
// remove all child nodes
while (dv.hasChildNodes()) {
dv.removeChild(dv.lastChild);
}
var img = document.createElement("IMG");
img.src = "images/hangman_0.gif";
dv.appendChild(img);
If you want to replace an element, you need to use replaceChild, not appendChild.
I would not recommend changing the src of the element in question. That would cause a lag in the display of the next image while the browser downloads the next image. If you have a set number of images you would want to preload them the way you are doing so now.
If you have the following code:
<div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>
You can do this:
<script type="text/javascript>
var nextImage = document.createElement("img");
nextImage.src = "your source here";
document.getElementById("imgDiv").appendChild(nextImage);
</script>
Now that you have an image in place you can use the replaceChild() method:
var imageDiv = document.getElementById("imgDiv");
imageDiv.replaceChild(nextImage, imageDiv.childNodes[0]);

Categories