Displaying Images in Javascript - javascript

OK, so I'm making a website in HTML, and it's working great, but I need to know how to display images on the page in javascript. I have in my website where there is a part on the homepage called news, and it's going to display an image about the topic, but I don't know how to display the image. When I use other website's ways, the image just displays as a square with a ? in the middle. Please help!!

var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.appendChild(content);
I got these answers from:
How to display image with javascript?
How to append data to div using javascript?

This will work:
DEMO
javascript:
var i = document.getElementById('test'); //get the element to put the picture in
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>'; // append the picture to the divs inner HTML
HTML:
<div id="test"></div>
Or without HTML in the first place (of course you need html and body tag...)
DEMO2
Code:
var i = document.createElement('div');
i.id = 'test';
document.getElementsByTagName('body')[0].appendChild(i);
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>';

Related

How to display an array of images as a list and make them clickable to display some text using javascript?

I need to display a list of images from an array and also make it clickable to display some text on click. Looking for some simple solution only with javascript.
var images = ["img1", "img2", "img3"];
var allPics = images.length;
var i = 0;
for(;i<allPics; i++){
myImg.src = images[i];
}
Example here:
https://jsfiddle.net/gmqLtd1u/1/
Now only one image is displayed.
Now only one image is displayed.
Because you're using one <img> and update its src several times in loop. After last iteration, its src is not updated anymore. That's why you see the last image.
Change your html, so that instead of <img> you have <div> as container/placeholder:
<!-- <img id="myImg"/> -->
<div id="myImg"></div>
And change your JS, to create <img> and append it to <div>:
for(;i<allPics; i++){
// myImg.src = images[i];
// TODO: adjust this to whatever you want
// in this example, use `<a>` that link to another page
// you can use javascript to show modal/alert too
var a = document.createElement('a');
a.href = 'example.html'; // TODO: adjust this
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}
And maybe your CSS, to match with new output:
#myImg img {
...
}

Set an image from Firebase as the background of div via jQuery

I'm trying to get an image from fire base and set it as the background of a div. Does anyone know how to do that? I tried all of my ideas and they did not work. Can someone provide any examples?
<div class="museBGSize rounded-corners grpelem" id="u525"></div>
I tried it this way and it didn't work:
fbRef4.on("child_added", snap => {
var image = snap.child("Image").val();
//concatenated the img tag using the image variable at the top
$("#tableBody3").append("<img src=" + image + "/img>");
});
hello every one i found an answer for it and will post the answer just in case if some one want to know
((my html))
<div class="museBGSize rounded-corners grpelem" id="u525"><!-- simple frame --></div>
((my js))
var fbRef4 = firebase.database().ref().child("slide");
fbRef4.on("child_added", snap => {
var image = snap.child("Image").val();
var newimgsrc = 'image' + (new Date().getTime());
var newimg = $('#u525');
$('#u525').css("background-image", "url("+image+")");
newimg.css({'background-image': 'url('+image+')'});
newimg.show();
});
((my firebase))
-slide
-asdasdasd
Image:"https://firebasestorage.googleapis.com/v0/b/awe..."

Generate html using Javascript

I have a gallery page that is updated often with new images. I use simple HTML to post the photos. My process currently is copy and paste the set of tags for a photo and change the number to correspond with the image file name. E.G. I change the number 047 to 048. Copy-Paste, change it to 049. This goes on until I have reached the number of additional photos. As you can see, this is very inefficient and there must be a better way of doing this. I was wondering if there is a simpler way to achieve this with Javascript? Perhaps generate additional tags by inputing a certain number or range?
Any ideas that would make this process efficient are welcomed please! Thank you!
<div class="cbp-item trim">
<a href="../assets/images/trim/img-trim-047.jpg" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="../assets/images/trim/img-trim-047.jpg" alt="">
</div>
</a>
</div>
You could use a templating solution. There are several libraries for that, but you can also implement it yourself.
Here is one way to do that:
Put the HTML for one image in a script tag that has a non-standard language property so the browser will just ignore it
Put some keywords in there that you'll want to replace, e.g. {url}. You can invent your own syntax.
Read that template into a variable
In the JS code, put all the images' URLs in an array of strings
For each element in that array, replace the keywords in the template string with that particular URL, and concatenate all these resulting HTML snippets.
Inject the resulting HTML into the appropriate place in the document.
Here is a snippet doing that:
// Add new images here:
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/330px-SNice.svg.png",
"https://nettemarie357.files.wordpress.com/2014/09/smiley-face.jpg?w=74&h=74",
];
// Load the template HTML
var template = document.querySelector('script[language="text/template"]').innerHTML;
// Use template to insert all the images:
container.innerHTML = images.map(url => template.replace(/{url}/g, url)).join('');
img { max-width: 50px }
<div id="container"></div>
<script language="text/template">
<div class="cbp-item trim">
<a href="{url}" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="{url}" alt="">
</div>
</a>
</div>
</script>
This would help you creating it programatically:
var new_row = document.createElement('div');
new_row.className = "cbp-item trim";
var a = document.createElement('a');
a.href = "../assets/images/trim/img-trim-047.jpg";
a.className= "cbp-caption cbp-lightbox";
document.body.appendChild(a);
var div = document.createElement('div');
div.className = "cbp-caption-defaultWrap";
var img = document.createElement('img');
img.src= "../assets/images/trim/img-trim-047.jpg";
div.appendChild(img);
a.appendChild(div);
new_row.appendChild(a);
If it is just about printing HTML, I suggest you to use plugins like Emmet for Sublime Text editor.
When you install this plugin and see how it works, you can simple create a complex html in a way that 'for' loop would do this. This will help you to change only the image/link number of every item.
Check the demo in the link, that I added.
Here's an example in Java Script that will generate the html you will need. Set the total to whatever number you need to generate the number of images you want.
var total = 47;
var hook = document.getElementById('hook');
// Main Node for SlideShow
var node = document.createElement('div');
node.classList = "cbp-item trim";
// Work out the correct number
var n = function(int) {
var length = int.toString().length;
return length === 1
? '00' + int
: length === 2
? '0' + int
: length
}
// Create the item
var createItem = function(int){
// Create Anchor
var a = document.createElement('a');
a.href = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg" class="cbp-caption cbp-lightbox';
a.classList = 'cbp-caption cbp-lightbox';
// Create Div
var div = document.createElement('div');
div.classList = 'cbp-caption-defaultWrap';
// Create Image
var img = document.createElement('img');
img.src = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg';
img.alt = 'gallery image';
// Finalise Dom Node
var container = div.appendChild(img)
a.appendChild(div);
// Return Final Item
return a
}
// Create Items
for (var i = 1; i < total + 1; i++) {
node.appendChild(createItem(i));
}
// Append Main Node to Hook
hook.appendChild(node);
<div id="hook"></div>

return image as HTML

trying to add an image to my innerHTML.
Looked at a few prvious Q's
Why does my image not show up when I use Javascript innerHTML to call it?
Javascripts innerHTML not working for images, but works with text?
I cant get it working, in google dev tools throws the error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
with this line:
var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>";
my code looks like:
function showImage() {
var img = document.createElement('image');
//var newImage = document.getElementById('img').innerHTML = "<a href='#'><img src='http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg' border=0/></a>";
var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>";
var div5 = document.createElement('div');
div5.appendChild(newImage);
return div5.innerHTML;
}
I know there are many other methods to display an image, but for the purpose of this exercise I want to return the image as an innerHTML
Try this :
var img = document.createElement("img");
img.setAttribute('src', 'http://www.domain.com/imgSrc');
var div5 = document.createElement('div');
div5.appendChild(newImage);
document.createElement('image') creates a new html tag: <image> i suspect you're trying to add a div and apply the image as inner html. you can fix this code like the following:
function showImage() {
var img = document.createElement('div');
document.body.appendChild(img)
img.innerHTML = "<img src='images/bg-main.png></img>";
}

is it possible to display pictures in a popup.php window, using the src from the main page?

I have a page with pictures, which I want to displayed in a popup.php when clicking on them.
I want the popup window to display a picture(the one I'm clicking on), some text, and a print button.
I'm doing this on the page:
<img src="graphics/picture1.png" width="340" height="200" border="0"/>
In the JS file:
function popup()
{
window.open('popup.php', 'window', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
}
function showImg(img)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
}
And in the popup.php:
<img src="graphics/picture03.png" onload="showImg(this)" />
There should be an obvious way, but I can't find it.
I would think adding the image name and text content to the URL would be the obvious way.
popup.php?image=myImage.gif&text=Say%20something%20witty%20here
Well, you'll want to have your popup contain a holder for the image (which it seems like you already have), but you'll also need to have a holder for your text. Your popup.php should have something like <div id="textHolder"></div> - then your javascript function needs to accept the appropriate text as well as populate it into the textHolder div.
I'm not sure how you're calling these JS functions, or from where - so some of the code might need to change - it should be something to the tune of....
function showImg(img, textHolderObj, text)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
textHolderObj.innerHTML= text
}
If is that simple, you could create it:
var win = window.open('', 'win', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
var img = win.document.createElement('img');
img.src = 'image.png';
img.alt = 'Some text';
var label = win.document.createElement('p');
label.innerHTML = 'Some text';
var button = win.document.createElement('a');
button.href = 'javascript:window.close()';
button.innerHTML = 'Close';
win.document.body.appendChild(img);
win.document.body.appendChild(label);
win.document.body.appendChild(button);
I don't get the question too well. You want to access a function that was defined in the page that opened a popup? You should be able to use opener.showImg(this)
your popup has no idea what image you clicked on. you need to do this:
onClick="popup('imgSrc')"
and in your window reference:
window.open('popup.php?imgSrc='+imgSrc, ...
then... your popup window has to run off of url vars, but php now knows what its looking for:
<?php echo '<img src="' . $_GET["imgSrc"] . '" />'; // this is going to load the image, so you don't need the onLoad()
It is possible to create a new popup window using a variable
top.mydocument=window.open('','window','toolbar=no,location=no,
status=no,menubar=no,scrollbars=no,resizable=no,
width=520,height=400,left=350,top=100');
and then use document.write to write the content:
top.mydocument.document.write(
'<html><head></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+'imageName/imagePath.png'
+'</body></html>'
)
Make sure you close it.
top.mydocument.document.close()

Categories

Resources