Reputation: 37
What would be the best way to write a much cleaner version of this. I have some ideas but would love a second opinion here.
$('.screenshot1').click(function(){
$('#screenshot1').show();
});
$('.screenshot2').click(function(){
$('#screenshot2').show();
});
$('.screenshot3').click(function(){
$('#screenshot3').show();
});
$('.screenshot4').click(function(){
$('#screenshot4').show();
});
$('.screenshot5').click(function(){
$('#screenshot5').show();
});
$('.screenshot6').click(function(){
$('#screenshot6').show();
});
$('.screenshot7').click(function(){
$('#screenshot7').show();
});
$('#screenshot1, #screenshot2, #screenshot3, #screenshot4, #screenshot5, #screenshot6, #screenshot7, .modal-backdrop').click(function() {
$('#screenshot1').hide();
$('#screenshot2').hide();
$('#screenshot3').hide();
$('#screenshot4').hide();
$('#screenshot5').hide();
$('#screenshot6').hide();
$('#screenshot7').hide();
});
HTML Looks like this:
<a class="screenshot1" href="#"></a>
<div id="screenshot1">
<img src='homepage/screenshot1.jpg' alt='Screenshot 1' height='565' width='756' />
</div>
etc....
Thanks!
Upvotes: 0
Views: 87
Reputation: 2639
I would do something like this:
html:
<div class="container">
<div class="screenshot">
<img src="image.png"/>
</div>
</div>
Apply the same class to all your screenshots:
$('.screenshot').click(function(){
$(this).parent('.container'). find('.screenshot') .each(function () {
$(this).hide();
});
$(this).show();
});
Upvotes: 0
Reputation:
Not 100% sure if this is what you mean, but I hope it helps in finding your right approach:
'use strict';
$(document).ready(function(){
$('[class^="screenshot"]').click(function(){
// Hide them all
$('[id^="screenshot"]').hide();
// Show only the clicked one
var id_name = $(this).attr('id');
$('#' + id_name).show();
});
});
Good luck!
Upvotes: 0
Reputation: 40318
$("[class^=screenshot]").click(function() {
$('[id^="screenshot"]').hide();
var id = this.className.match(/screenshot(\d+)/)[1];
$('#'+id).show()
}
Upvotes: 2
Reputation: 67207
you can simplify your first block of code by using the following,
$(".screenshot1, .screenshot2, .screenshot3, .screenshot4, .screenshot5, .screenshot6, .screenshot7").click(function(){
$("#" + $(this).attr("class")).show();
});
Upvotes: 0
Reputation:
I would use a single selector for all the screenshot IDs and then use the each method. Edit: PSR's answer is better.
Upvotes: 1