patternjavascriptMinor
Click handlers for SVG polygons
Viewed 0 times
clickhandlerssvgforpolygons
Problem
How can I write this shorter?
$('#pietra_svg #p1_4 polygon#p1').click(function() {
$('#apla_p1').fadeIn("slow");
return false;
});
$('#pietra_svg #p1_4 polygon#p2').click(function() {
$('#apla_p2').fadeIn("slow");
return false;
});
$('#pietra_svg #p1_4 polygon#p3').click(function() {
$('#apla_p3').fadeIn("slow");
return false;
});
$('#pietra_svg #p1_4 polygon#p4').click(function() {
$('#apla_p4').fadeIn("slow");
return false;
});
$('#pietra_svg #p5 polygon#a').click(function() {
$('#apla_p5').fadeIn("slow");
return false;
});
$('#pietra_svg #p5 polygon#b').click(function() {
$('#apla_p5').fadeIn("slow");
return false;
});
$('.close').click(function() {
$('.apla').fadeOut("slow");
return false;
});Solution
You can use an array in a similar way here. Just leave the last one, as it doesn't fit the same pattern.
$.each(
[
{ poly: 'p1', id: '#apla_p1' },
{ poly: 'p2', id: '#apla_p2' },
{ poly: 'p3', id: '#apla_p3' },
{ poly: 'p4', id: '#apla_p4' },
{ poly: 'a', id: '#apla_p5' },
{ poly: 'b', id: '#apla_p5' }
],
function(o){
var id = o.id; // copy to closure
$('#pietra_svg #p1_4 polygon#' + o.poly).click(function() {
$(id).fadeIn("slow");
return false;
});
}
);
$('.close').click(function() {
$('.apla').fadeOut("slow");
return false;
});Code Snippets
$.each(
[
{ poly: 'p1', id: '#apla_p1' },
{ poly: 'p2', id: '#apla_p2' },
{ poly: 'p3', id: '#apla_p3' },
{ poly: 'p4', id: '#apla_p4' },
{ poly: 'a', id: '#apla_p5' },
{ poly: 'b', id: '#apla_p5' }
],
function(o){
var id = o.id; // copy to closure
$('#pietra_svg #p1_4 polygon#' + o.poly).click(function() {
$(id).fadeIn("slow");
return false;
});
}
);
$('.close').click(function() {
$('.apla').fadeOut("slow");
return false;
});Context
StackExchange Code Review Q#5848, answer score: 3
Revisions (0)
No revisions yet.