4
\$\begingroup\$

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;
});
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

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;
});
\$\endgroup\$
0
0
\$\begingroup\$

There are lots of id's you shouldn't use, if #p1 is unique (as it should), $('#p1') should be the same as $('#pietra_svg #p1_4 polygon#p1'). You should try to review your svg tags,

You can also cache the root of the query, saving a lot of time searching the dom:

var pietra = $('#pietra_svg')

and then

pietra.find('#p1_4 polygon#p1')

Also, for the first four elements you may bind them once, and with the clicked element id, find element to fade:

pietra.find('#p1_4 polygon').click(function() {
  $('#apla_' + this.id).fadeIn("slow");
  return false;
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.