Adding image using javascript - javascript

I have a html page in which there is an image in anchor tag code is :
<img src="images/test.png" />
on body onload event i am calling a javascript function which dynamically changes the image . My code is:
<script type="text/javascript">
function changeImage()
{
document.getElementById('x').innerHTML= '<img src="images/test2.png" />';
}
</script>
This is working fine in firefox but not working in google chrome and ie. Please help..

try this:
<img id="y" src="images/test.png" />
in js
function changingImg(){
document.getElementById("y").src="./images/test2.png"
}
Tested in Chrome and IE.
Then try this: [hoping that id of <a> is available and have at least one img tag]
var x = document.getElementById("x");
var imgs = x.getElementsByTagName("img");
imgs[0].src="./images/img02.jpg";

try following instead of changing innerHTML.
function changeImage()
{
var parent = documeent.getElementById('x');
parent.getElementsByTagName("img")[0].src = "newUrl";
}

As others have indicated, there are many ways to do this. The A element isn't an anchor, it's a link. And no one really uses XHTML on the web so get rid of the XML-style syntax.
If you don't have an id for the image, then consider:
function changeImage(id, src) {
var image;
var el = document.getElementById(id);
if (el) {
image = el.getElementsByTagName('img')[0];
if (image) {
image.src = src;
}
}
}
Then you can use an onload listener:
<body onload="changeImage('x', 'images/test.png');" ...>
or add a script element after the link (say just before the closing body tag) or use some other strategy for running the function after the image is in the document.

Related

JS: Can't remove created Element in IE

I'm dynamically creating an image via javascript like this:
var dragimg = null;
function createImage(g) {
dragimg = document.createElement("img");
dragimg.src = "link/to/image.png";
dragimg.style.width = "50px";
dragimg.style.position = "absolute";
dragimg.style.zIndex = 100;
$("body").prepend(dragimg);
}
After creating the Image, I want to remove it at some point by calling this function:
function removeImage() {
dragimg.remove();
}
This works well in Chrome, Firefox & Opera. However, it doesn't work in Internet Explorer 11.
I'd also like to point out I have an document.onmousemove function set which manipulates the left and top attribute of the created image when the mouse moves. This works well in all browsers - but I'm not sure if it has something to do with the remove-problem.
I've also tried to remove the image by dragimg.parentNode.removeChild(dragimg), but same result.
A few things other than the classic just-use-jquery answer:
element.remove() is not supported yet by Internet Explorer, according to the API: http://msdn.microsoft.com/en-us/library/ie/hh772117(v=vs.85).aspx. It's an experimental technology: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove
Are you sure parentNode.removeChild isn't working because it is for me: http://jsfiddle.net/limdauto/wztm1dgk/
Before
After
To use jQuery remove method you need this:
function removeImage() {
$(dragimg).remove();
}
Your dragimg is a dom element, but $(dragimg) is a jQuery element. While jQuery prepend method accepts dom elements, remove does not - it applies to jQuery element itself or to selector. More about jQuery remove and prepend.
I'm not sure the context where you are calling the removeImage function, but the code below demonstrates inserting the image element and removes it after an interval of 2 seconds.
Note: Replace the path to your image.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var dragimg = null;
function createImage(g) {
dragimg = document.createElement("img");
dragimg.src = "someimage.jpg";
dragimg.style.width = "50px";
dragimg.style.position = "absolute";
dragimg.style.zIndex = 100;
$("body").prepend(dragimg);
}
function removeImg() {
dragimg.parentNode.removeChild(dragimg);
}
createImage(null);
window.setInterval(removeImg, 2000);
</script>
</body>
</html>

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.

Setting img tag's src as the result of a javascript function

I have a function getImgurUrl() and I want what it returns to be the src value of a img tag.
How can I do this?
my function:
function getImgurUrl() {
//get imgur url for current image
var cookieArray = document.cookie.split(";");
var encodedURL = cookieArray[2].split("=");
var decodedURL = decodeURIComponent(encodedURL[1]);
return decodedURL;
}
and img tag:
<img id="image" name="image" src="" alt="If you're seeing this something is wrong.">
window.onload = function() {
document.getElementById("image").src = getImgurUrl();
};
function getImageUrl(imageId) {
return document[imageId].src;
}
<img id="mike" src="http://yoursite.com/images/1.jpg" />
I haven't tested this but you get the idea.
I'm not sure what you're doing with the cookie logic so just kept example simple.
--
I would recommend you add jQuery to handle cross-browser compatibility as getElementById or others may not work all the time and all versions, also document. might not as well and sometimes it's window.functionName()
In jQuery you would reference the image src similarly but in my return, you'd concat a pound symbol with the id:
return $('#' + id).src;

append string to image src using js

I've got a page where there is <img src="/images/product/whatever-image.jpg" alt="" />
I want it so that upon loading of the page, the string "?Action=thumbnail" is appended to src's value, making it src="/images/product/whatever-image.jpg?Action=thumbnail"
how do I achieve this using js?
window.addEventListener('load', function(){
/* assuming only one img element */
var image = document.getElementsByTagName('img')[0];
image.src += '?Action=thumbnail';
}, false);
Note, changing the source of the image will "re-fetch" the image from the server — even if the image is the same. This will be better done on the server-side.
Update after comment:
window.addEventListener('load', function(){
/* assuming only one div with class "divclassname" and img is first child */
var image = document.getElementsByClassName('divclassname')[0].firstChild;
image.src += '?Action=thumbnail';
}, false);
Use this:
window.onload = function() {
document.getElementById('myImage').src += "/Action=thumbnail";
};

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>

Categories