return image as HTML - javascript

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

Related

Populate an input field with an image src in javascript

I have an XHR response that returns images. I have my function in order to show the images. I am combining JQuery and JS in the same code snippet. So far all is working well:
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var lien = leselements[i].url;
//place image urls in img src
output += "<img src='" + lien + "' class='imgs'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;}
But I would like to allow users to click an image and then populate an input field ('#imageurl') with the clicked image src. Here is what I tried but it does not work.
$('.imgs img').click(function(){
$('#imageurl').val() = "";
var source = $(this).attr('src');
$('#imageurl').val() = source;
});
Any help will be greatly appreciated. TIA.
Using .val() in this way will just return the current value of #imageurl.
$('#imageurl').val()
.val is a function call that works as a getter and a setter.
To set the value, try this:
$('#imageurl').val(source);
$('#imageurl').val("");
// ...
$('#imageurl').val(source);
See the documentation.
Try this:
$('img.imgs').click(function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
If the image will be rendered after the attachment of the event handler use this:
$('img.imgs').live('click', function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
Thank you guys for your prompt answers. I tried all of them but they did not work for me. I then asked a friend and we finally found a way to make it work. Probably not the best or professional way but it works. Here is the solution if ever anyone needs it.
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var link = leselements[i].url;
//Place urls in image src and pass in 'link' parameter to the getsrc function
output += "<img src='" + link + "' onclick='getsrc(\""+link+"\")'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;
}
function getsrc (link) {
//console.log($(this));
$('#imageurl').val("");
// var source = $(this).attr('src');
//place imageurl value by passing in the link parameter.
$('#imageurl').val(link);
}

I get an error on trying to get the img.src from my Html textfield

The following is my function that is called on click of a button.
The goal is to get the text value entered by the user and use it as an image source and finally display the image on the html body.
function ButtonClick() {
var link = document.createElement("a");
// create an image element.
var MyImg = document.createElement("img");
var MyImg.src = document.getElementById("textfield").value;
// append it to a list of elements.
link.appendChild(MyImg);
// append the newly added image to the html page body.
document.body.appendChild(link);
// clear textfield for next image src.
document.getElementById("textfield").value = "";
}
The error I receive is on line#7: "var MyImg.src = document.getElementById("textfield").value;"
SyntaxError: missing ; before statement example.js:19
*edited code after the fist suggestion.
MyImg.src = document.getElementById("textfield").value;
you should define variable once,
change
var MyImg = document.createElement("img");
var MyImg.src = document.getElementById("textfield").value;
to
var MyImg = document.createElement("img");
MyImg.src = document.getElementById("textfield").value;

Displaying Images in 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>';

Display image through html image element object

I have the following code :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
}
pastedImage.src = source;
}
The function createImage contain the source parameter which contain the source of an image. After that I created the object pastedImage of class Image and after alerting that I am getting the html image element object like [object HTMLImageElement].
My question is how I can display image into my html page using that object. I want to display it after onload function.
Hiya : Working demo http://jsfiddle.net/wXV3u/
Api used = .html http://api.jquery.com/html/
In demo click on the click me button.
Hope this helps! Please lemme know if I missed anything! B-)
Code
$('#foo').click(function() {
createImage("http://images.wikia.com/maditsmadfunny/images/5/54/Hulk-from-the-movie.jpg");
});
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
}
pastedImage.src = source;
$(".testimonialhulk").html(pastedImage);
}​
Also you can do like this :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Your image in canvas: <img src="'+pastedImage.src+'" height="100" width="200"/>');
}
pastedImage.src = source;
}​
Simple, and better, using javascript dom primitive (replaceChild):
Get the parent of the image, the div or span that contains it, and replace the old img tag with the new image object you created with your function
var domImgObj = document.getElementById("image");
var imgObj = createImage(src); // your function
imgObj.id = pageimgObj.id; // necessary for future swap-outs
document.getElementById("container").replaceChild(imgObj,domImgObj);
document.createRange().createContextualFragment(img.outerHTML)
Example
const img = new Image()
img.src = "https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico"
const frag = document.createRange().createContextualFragment(`${img.outerHTML}`)
document.querySelector(`body`).append(frag)

displaying photo?

I was trying to do this in an alert box only to find out that I can't now. I cannot manage to get this to display at all. Instead of the variable I get [object HTMLImageElement]. I am missing something but what is it?
function joePic(){
var joe_fat = new Image;
joe_fat.src = "pic1.jpg";
document.getElementById('photo').innerHTML = joe_fat;
}
<input type="button" value="Click here it find out" name="joePhoto" onclick="joePic()"
height="150" width="150" />
Well, you're trying to assign an Image as HTML, but it's not HTML. It's an Image.
You have two options:
Append joe_fat into the #photo element using the proper DOM function (which is appendChild) instead of pretending it's a string of HTML:
function joePic() {
var joe_fat = new Image;
joe_fat.src = "pic1.jpg";
var photoElm = document.getElementById('photo');
photoElm.innerHTML = ''; // clear target first
photoElm.appendChild(joe_fat); // now add image
}
Get rid of the Image object and actually do present a string of HTML instead:
function joePic() {
document.getElementById('photo').innerHTML = '<img src="pic1.jpg" />";
}
Use appendChild() instead of innerHTML:
function joePic(){
var joe_fat = new Image;
joe_fat.src = "pic1.jpg";
document.getElementById('photo').appendChild(joe_fat);
}
To do this via innerHTML (which isn't the preferred method), you would need to set #photo's innerHTML property to be the actual <img> markup, as in:
document.getElementById('photo').innerHTML = "<img src='pic1.jpg' alt='alttext' />";
This would overwrite any existing contents of #photo. The correct method is to use appendChild() to manipulate the DOM.
function joePic() {
var joe_fat = new Image();
joe_fat.src = "pic1.jpg";
document.getElementById('photo').appendChild(joe_fat);
}

Categories

Resources