Reputation: 315
I need to show/hide multiple divs based on what the user clicks on.
So they click on a link:
<a href="#" id="image1">Click me to show</a>
Which then shows the div using jQuery:
$(document).ready(function(){
$("#image1").click(function () {
$("#image1_view").fadeIn();
return false;
e.preventDefault();
});
});
What I need to do is do this multiple times so there are multiple links on a page which, when clicked on, show the correct div.
Short of copying & pasting the above code loads of times, what is the easier way to do it? How can I pass an ID of the link to the jQuery so that it knows which div to show?
Thanks!
Upvotes: 0
Views: 167
Reputation: 318302
Assuming both links and images have ID's that resemble one another, like:
<a href="#" id="image1">Click me to show</a>
<a href="#" id="image2">Click me to show</a>
<a href="#" id="image3">Click me to show</a>
<img src="img1.png" id="image1_view" />
<img src="img2.png" id="image2_view" />
<img src="img3.png" id="image3_view" />
etc, you could do:
$(document).ready(function(){
$('a[id^="image"]').on('click', function(e) {
e.preventDefault();
$('#'+ this.id +'_view').fadeIn().one('click', function() {
$(this).fadeOut();
});
});
});
Upvotes: 2
Reputation: 7068
Give all your <a>
tags dummy css class (ex. ClassName1)
Edit the Code so that it looks like:
$(document).ready(function(){
$(".ClassName1").click(function () {
$("#" + this.id + "_view").fadeIn();
return false;
e.preventDefault();
});
});
where you maintain the IDs of Divs to be the ImageID_view
Upvotes: 0
Reputation: 53238
Assuming that you can give the div
elements to be faded in an ID, this should work (pass the ID reference inside the a
element's href
attribute):
$('a.fadeIn').on('click', function(e) {
e.preventDefault();
var the_div = $($(this).attr('href'));
the_div.fadeIn('fast');
});
Upvotes: 0