displaying photo? - javascript

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

Related

Image Swap on MouseOut (JavaScript, not JQ)

I am trying to create functions to mouseover and mouseout of images. The tricky part is this function needs to work for any image, and I cannot use direct image names. I have to therefore use variables.
The HTML code is as follows for the images:
The HTML for the images is like this, and there are 3 images:
<img src="images/h1.jpg" alt="" id="images/h4.jpg" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I'm expecting that you have to reference the id for the new image, and then the src attribute for the previous image to revert when you mouseout.
The problem is that, if I reference the id attribute, the image no longer has information on the src attribute so I cannot call it to revert back.
Here is the JavaScript I have thus far. It works to swap the image to a new one, but not to swap it back :(
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var ulTree = $("image_rollovers");
var imgElements = ulTree.getElementsByTagName("img");
//PROCESS EACH IMAGE
//1. GET IMG TAG
for (var i = 0; i < imgElements.length; i++) {
console.log (imgElements[i]);
console.log (imgElements[i].getAttribute("src"));
//2. PRELOAD IMAGE FROM IMG TAG
var image = new Image();
image.setAttribute("src", imgElements[i].getAttribute("src"));
//3. Mouseover and Mouseout Functions Called
image.addEventListener("mouseover", swapToNewImage);
image.addEventListener("mouseout", swapImageBack);
}
}
//MOUSE EVENT FUNCTIONS
var swapToNewImage = function(img) {
var secondImage = img.getAttribute("id", "src");
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.getAttribute("src");
img.src = previousImage;
}
Let me know if you can help me figure out how to call the image's src attribute so it can be reverted back. Again, I cannot reference specific image names, because that would be a lot easier (: Thank you!
Well, You can use a data attribute to store your src, and a data attribute to store the image you want to swap when mouseover.
Please try the following example.
var swapToNewImage = function(img) {
var secondImage = img.dataset.swapSrc
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.dataset.src
img.src = previousImage;
}
<img src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" data-src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-swap-src="https://images.pexels.com/photos/416160/pexels-photo-416160.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I also notice that the image tag is generated by code, in order to set the dataset values, we can do this:
var image = new Image();
image.scr = [src]
image.dataset.src = [src]
image.dataset.swapSrc = [swap src]

Adding different images to a form according to name using if/else

I am trying to insert image values into the html to replace the src according to the name so if the name for the templateName = Javascript I can make the src value = something like say (http://www.w3devcampus.com/wp-content/uploads/logoAndOther/logo_JavaScript.png) and do that for other categories as well using an if/else statement in javascript.
my script look like this but it has a few errors with the syntax
var imageChoosernator = function () {
if (#templateName == "Javascript")
{
img = <img src="htp://www.w3devcampus.com/wp-content/uploads/logoAndOther/logo_JavaScript.png">;
}
` }
Can someone guide me toward the proper solution?
# in #templateName is wrong. Know your allowed variable characters.
img = <img the <img is an unstarted String. Know how to enclose values into String.
` <<< you cannot have such character floating around your code (hopefully just an edit typo).
Since you didn't showed most of your code, a fix would be something like:
var img = "";
var templateName = "Javascript";
function imageChoosernator () {
if (templateName === "Javascript") { // remove unallowed #
img = '<img src="js.png">'; // enclose into String
} else {
img = '<img src="someting.png">';
}
// Finally append img to element #imgContainer
document.querySelector("#imgContainer").insertAdjacentHTML("beforeend", img );
}
imageChoosernator(); // Do the magic
You can use jQuery .prepend() method to replace the image src on loading the query into the page.
If in html you have given the id name as 'JavaScript' like-
div id="JavaScript"><img id="imgNew1" src="oldImg1.png" />
div id="templateName2"><img id="imgNew2" src="oldImg2.png" />
To change the image source following can be used-
$('#templateName1').prepend('<img id="imgNew" src="newImg1.png" />')
$('#templateName2').prepend('<img id="imgNew" src="newImg2.png" />')
You need to read the documentation here
To automatize the src change while creating intances of the same will go like-
<html>
<head>
<script type="text/javascript">
var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "firstImg.png" // set image object src property to an image's src, preloading that image in the process
slideimages[1] = new Image()
slideimages[1].src = "secondcarImg.png"
slideimages[2] = new Image()
slideimages[2].src = "thirdImg.png"
</script>
</head>
<body>
<img src="firstImg.img" id="slide" width=100 height=56 />
<script type="text/javascript">
//variable that will increment through the images
var step = 0
var whichimage = 0
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
whichimage = step
if (step<2)
step++
else
step=0
}
</script>
</body>
</html>

HTML JavaScript delay downloading img src until node in DOM

Hi I have markup sent to me from a server and I set it as the innerHTML of a div element for the purpose of traversing the tree, finding image nodes, and changing their src values. Is there a way to prevent the original src value from being downloaded?
Here is what I am doing
function replaceImageSrcsInMarkup(markup) {
var div = document.createElement('div');
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(replaceSrc);
return div.innerHTML;
}
The problem is that in browsers as soon as you do:
var img = document.createElement('img'); img.src = 'someurl.com' the browser fires off a request to someurl.com. Is there a way to prevent this without resorting to parsing the markup myself? If there is in no other way does anyone know a good way of parsing the markup with as little code as possible to accomplish my goal?
I know you are already happy with your solution, but I think it would be worth sharing a safe method for future users.
You can now simply use the DOMParser object to generate an external document from your HTML string, instead of using a div created by your current document as container.
DOMParser specifically avoids the pitfalls mentioned in the question and other threats: no img src download, no JavaScript execution, even in elements attributes.
So in your case you can safely do:
function replaceImageSrcsInMarkup(markup) {
var parser = new DOMParser(),
doc = parser.parseFromString(markup, "text/html");
// Manipulate `doc` as a regular document
var images = doc.getElementsByTagName('img');
for (var i = 0; i < images.length; i += 1) {
replaceSrc(images[i]);
}
return doc.body.innerHTML;
}
Demo: http://jsfiddle.net/94b7gyg9/1/
Note: with your current code, browsers will still try downloading the resource initially specified in your img nodes src attribute, even if you change it before the end of JS execution. Trace network transactions in this demo: http://jsfiddle.net/94b7gyg9/
Rather than append the new markup to the DOM before you change the img sources, create an element, set it's inner HTML, change the source of the images and then finally, append the changed markup to the page.
Here's a fully-worked sample.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
//function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
//function newTxt(txt){return document.createTextNode(txt);}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('goBtn').addEventListener('click', onGoBtnClick, false);
}
var dummyString = "<img src='img/girl.png'/><img src='img/gfx07.jpg'/>";
function onGoBtnClick(evt)
{
var div = newEl('div');
div.innerHTML = dummyString;
var mImgs = allByTag('img', div);
for (var i=0, n=mImgs.length; i<n; i++)
{
mImgs[i].src = "img/murderface.jpg";
}
document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>GO!</button>
</body>
</html>
You could directly parse the markup string using a regex to replace the img src. Searching for all the img src urls in the string and then replacing them with the new url.
var regex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
var imgUrls = [];
while ( m = regex.exec( markup ) ) {
imgUrls.push( m[1] );
}
imgUrls.forEach(function(url) {
markup = markup.replace(url,'new-url');
});
Another solution might be, if you have access to it, to set the all the img src to an empty string, and put the url in in a data-src attribute. Having your markup string look like something like this
markup = '
';
Then setting this markup to your div.innerHTML won't trigger any download from the browser. And you can still parse it using regular DOM selector.
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(function(img){
var oldSrc = img.getAttribute('data-src');
img.setAttribute('src', 'new-url');
});

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

object HTMLImageElement showing instead of image

I created an array of 2 images and tried to display them, but instead of the images I got the text:
object HTMLImageElement
I am sure my images are in the right directory which I am currently working with.
< template is="auto-binding">
<section flex horizontal wrap layout>
<template repeat="{{item in items}}">
<my-panel>{{item}}</my-panel>
</template>
</section>
<script>
(function() {
addEventListener('polymer-ready', function() {
var createImage = function(src, title) {
var img = new Image();
img.src = src;
img.alt = title;
img.title = title;
return img;
};
var items = [];
items.push(createImage("images/photos/1.jpeg", "title1"));
items.push(createImage("images/photos/2.jpeg", "title2"));
CoreStyle.g.items = items;
addEventListener('template-bound', function(e) {
e.target.g = CoreStyle.g;
e.target.items = items;
});
});
})();
</script>
What am I missing here?
Use:
items.push(createImage(...).outerHTML);
Edit: Changes to original question has rendered the rest of the answer obsolete. But I am leaving it anyway in the hope that OP or someone may learn something.
I got the text: object HTMLImageElement
I am pretty sure you are using something like this to add the new element to DOM:
document.getElementById('#insert_image_here').innerHTML = items[0];
(Edit: What happens here is this: your newly created object items[0] is an HTMLImageElement. When you try to assign it to innerHTML, since innerHTML is type of String, JavaScript will try to call the objects toString() method and set the returned value to innerHTML. For DOM elements toString always returns object XElement.)
What you need to do is this:
document.getElementById('#insert_image_here').appendChild(items[0]);
The easiest and safest way to do this is to put the img in the template and bind the src and title attributes like this:
<template repeat="{{item in items}}">
<my-panel><img src="{{item.src}}" alt="{{item.title}}" title="{{item.title}}"></my-panel>
</template>
Then createImage looks like this
var createImage = function(src, title) {
return {src: src, title: title};
}
Replace
var createImage = function(src, title) {
var img = new Image();
img.src = src;
img.alt = title;
img.title = title;
return img;
};
With
var createImage = function(src,title) {
title = title.replace(/"/g,""");
return '<img src="'+src+'" title="'+title+'" alt="'+title+'" />';
}
It looks like whatever framework thingy you're using is expecting strings, not Image objects ;)

Categories

Resources