Reputation: 49
I am new in JS,please help me.I have 4 images with the same class name and a hidden div which is displayed when one of 4 images is clicked. How i can add to my div the image which one is clicked? I do not want to write a function for every image.Is it possible with my code?
<a href="#"><img onClick="show()"class="img" src="css/images1/img1.png"></a>
<a href="#"><img onClick="show()"class="img" src="css/images1/img2.png"></a>
<a href="#"><img onClick="show()"class="img" src="css/images1/img3.png"></a>
<a href="#"><img onClick="show()"class="img" src="css/images1/img4.png"></a>
<div class="gallery"></div>
<script>
function show(){
var x=document.getElementsByClassName('gallery')[0];
x.style.display="block";
x.innerHTML='<img src=css/images1/img1.jpg>';
};
</script>
Upvotes: 0
Views: 484
Reputation: 5964
Pass in the "src" of the element that was clicked:
function show(src){
var x=document.getElementsByClassName('gallery')[0];
x.style.display="block";
x.innerHTML = '<img src="' + src + '">';
}
Then for your html <img/>
tags pass in their src to show
:
<a href="#"><img onClick="show(this.src)"class="img" src="css/images1/img1.png"></a>
Edit: if you must select "gallery" by className, use getElementsByClassName
as you originally had.
Upvotes: 1