Reputation: 1440
I need some help with Jquery.
I have a div which contains multiple unique images and id's. When I click on the image with the id=image1 , I want to show the div imageinfo with the image1image class.
I dont want to show the image2image and image3image classes when I have clicked image1.
<style>
body{
width:100%;
height:100%;
margin:0px;
}
.imagecontainer img{
width:250px;
float:left;
}
.imageinfo{
background:white;
opacity:0.9;
width:100%;
height:100px;
position:absolute;
top:0px;
display:none;
}
#close{
position:absolute;
background:black;
color:white;
width:100px;
text-align:center;
padding-top:10px;
padding-bottom:10px;
top:30px;
right:30px;
}
</style>
<script>
$(document).ready(function(){
// hide information about image when button close is clicked
$(".close").click(function(){
$(this).parent().hide();
});
/* here I need the code to show the imageinfo and the image[number]image class
depending on which image was clicked.
*/
});
</script>
<!-- container -->
<div class="imagecontainer">
<img src="image1.png" id="image1">
<img src="image2.png" id="image2">
<img src="image3.png" id="image3">
</div>
<!-- image info -->
<div class="imageinfo">
<div class="image1image"><img src="image1.png"></div>
<div class="image2image"><img src="image2.png"></div>
<div class="image3image"><img src="image3.png"></div>
<div id="close">CLOSE</div>
</div>
Thanks so much for your help :)
Upvotes: 0
Views: 80
Reputation: 2788
first you need to know id of clicked image. Then set up element which to show it.
$('.imagecontainer img').click(function() {
// all hide
$('.imageinfo div').hide();
// get id of clicked img
var id = $(this).attr('id');
console.log(id);
// show info img
$('.imageinfo .'+id).show();
});
look at my solution
Upvotes: 2
Reputation: 218837
Something like this?:
$('img[id^="image"]').click(function () {
var id = $(this).attr('id');
$('div[class^="' + id + '"]').show();
});
This will bind a click event to every matching img
element, and in that event will get the id
of the element which was clicked and use that id
to select a div
to show.
You might even do this with a single click handler instead of one for each element. Something like this:
$('div.imagecontainer').on('click', 'img[id^="image"]', function () {
var id = $(this).attr('id');
$('div[class^="' + id + '"]').show();
});
That would attach only a single click handler to the containing div
and use event delegation to handle the click events.
Upvotes: 1