Javascript Get Image Source And Inject Into Another Image Source
Solution 1:
here is a working example. NOTE: a.getElementsByTagName('img')[0].src
as different browsers would add nodes to tag before and after the child tag. It is safe to use getElementsByTagName('img')[0].src
<html><head><scripttype="text/javascript">functionsetImg(a){
//alert(a.getElementsByTagName('img')[0].src);document.getElementById('ImageFrame').src =
a.getElementsByTagName('img')[0].src
}
</script></head><body><ahref="#"onclick="setImg(this);"><imgsrc="JCF/PICT0421.jpg"></a><div><imgid="ImageFrame"src="JCF/PICT0421.jpg"width="400" /></div></body></html>
Solution 2:
var pic1 = document.getElementById("image1");
var src = pic1.src; // here is the src for image1var pic2 = document.getElementById("image2");
pic1.src = src; // here we set the src for image2
So this code will take the image src
from image1 and put it in image2.
Solution 3:
I believe something like this should work for you:
HTML:
<ahref="#"onclick="setImage(this);"><imgclass="gallery"id="image1"src="image1.jpg" /></a>
Javascript:
functionsetImage(imgParent) {
document.getElementById("ImageFrame").src = imgParent.childNodes[0].src;
}
The Demo will work better when you actually load in images. However, if you inspect the broken images, you can see that it is loading in the new image correctly.
Edit:
Since Kaf mentioned that he has had issues with childNodes, you may want to try this out instead:
Javascript:
functionsetImage(imgParent) {
document.getElementById("ImageFrame").src = imgParent.getElementsByTagName('img')[0].src;
}
Solution 4:
assuming you can use Jquery
$('.imageClass').click(function(){
var srcToCopy = $(this).attr('src');
$(somewheretoputsrc).attr('src', srcToCopy);
})
this code should work
edit : fiddle edited with working image http://jsfiddle.net/jbduzan/b7adx/1/
Solution 5:
You should go with so called "Unobtrusive JavaScript", i.e. don't mix content with JavaScript and apply the desired behaviors after the window has been loaded. Something like that:
functionaddDomListener(element, eventName, listener) {
if (element.addEventListener) // most browsers
element.addEventListener(eventName, listener, true);
elseif (element.attachEvent) // IE
element.attachEvent('on' + eventName, listener);
}
window.onload = function() {
var elements = getElementsByClassName('thumb-link');
for (int i=0; i < elements.size(); i++) {
var el = elements[i];
addDomListener(el, "click", function () {
setImage(el);
});
}
}
getElementsByClassName still needs an implementation here and every a tag that had onlick previously needs the class 'thumb-link'. But I'm sure you'll figure that out.
Using a library like jQuery or Prototype.js would make it easier here...
Post a Comment for "Javascript Get Image Source And Inject Into Another Image Source"