views:

95

answers:

1

Page has menu items that would replace a 'div id=foo_(current menu item)' with 'div id=foo_(selected menu item)' in 'div class=foo'

Here's what I've got, and try to keep your breakfast down...

    $('#t1').click(function() {
        $('#attorney').show();
        $('#insurance,#financial,#estate,#trust,#death').hide();
    });

    $('#t2').click(function() {
        $('#insurance').show();
        $('#attorney,#financial,#estate,#trust,#death').hide();
    });

    $('#t3').click(function() {
        $('#financial').show();
        $('#attorney,#insurance,#estate,#trust,#death').hide();
    });

    $('#t4').click(function() {
        $('#estate').show();
        $('#attorney,#insurance,#financial,#trust,#death').hide();
    });

    $('#t5').click(function() {
        $('#trust').show();
        $('#attorney,#insurance,#financial,#estate,#death').hide();
    });

    $('#t6').click(function() {
        $('#death').show();
        $('#attorney,#insurance,#financial,#estate,#trust').hide();
    });
+2  A: 

Switch statements are kind-of ugly.

var things = ['attorney', 'estate', 'insurance', 'financial', 'trust', 'death'];
var guide = {
  t1: 'attorney', t2: 'estate', t3: 'insurance', t4: 'financial', t5: 'trust', t6: 'death'
};

$('#t1, #t2, #t3, #t4, #t5, #t6').click(function() {
  var clicked = $(this).attr('id');
  $.each(things, function(_, thing) {
    var $thing = $('#' + thing);
    if (guide[clicked] == thing) $thing.show(); else $thing.hide();
  });
});

You might also consider setting up the event handler with live() instead of directly on the "t" thingies, whatever they are. It would also be neater if all the "things" (attorney, etc) could be given a class name, because then you could just hide them all quickly in the click handler with

   $('.thingClass').hide();

and then just make the one visible that's appropriate for the tab that was clicked. Then it could look something like this:

var guide = {
  t1: 'attorney', t2: 'estate', t3: 'insurance', t4: 'financial', t5: 'trust', t6: 'death'
};
$('#t1, #t2, #t3, #t4, #t5, #t6').click(function() {
  $('.thingClass').hide();
  $('#' + guide[$(this).attr('id')]).show();
});

Finally, you might consider letting one of the available jQuery tab plugins handle this whole thing for you :-)

Pointy
Worked like a charm. Thanks.As for $('.thingClass').hide - would that be on a $(window).load(function() { ?As for the jQuery... I've had some issues with cross-contamination with other jQuery plugins on the page. There are several plugins on the page already. Javascript seems to be the least invasive solution.Again, thanks a lot.
Adam
No what I meant was that in the click handler, you'd just hide *everything*, and then call .show() for the one that's appropriate. It'd replace that "each" loop; I'll edit the answer to be more clear.
Pointy