1

So, to show and hide certain DIV tags within my site I got the following codes

$('#ONE').live('click', function () {
    $('.hide').css('display', 'none');
    $('#b-ONE').css('display', 'block');
});
$('#TWO').live('click', function () {
    $('.hide').css('display', 'none');
    $('#b-TWO').css('display', 'block');
});

where a click on the div namend "ONE" opens a certain "b-ONE" div, and so on. It works flawlessly but is a pain when the list gets longer. You see where it says "ONE" and "TWO" in the JS ... is there any way I can turn these "ONE" and "TWO" into variables, so I can have up to 40 divs and don't have to type the above code for every DIV, and have a sleek code where I only have to type that finction once with variables?

I'm looking into something like this but lack the in-depth JS / jQuery knowledge:

$('#VARIABLETEXT').live('click', function () {
    $('.hide').css('display', 'none');
    $('#b-VARIABLETEXT').css('display', 'block');
});

Where a click on a div named "TWENTYONE" shows the div "b-TWENTYONE"

Any help is highly appreciated!

Michael
  • 3,982
  • 4
  • 30
  • 46
  • 1
    At some point you should start planning to use the current suggested way(s) of binding jQuery event handlers. The `.live()` API has been deprecated for quite a while now (years). – Pointy Dec 23 '13 at 14:23

1 Answers1

4

Just use the id of the clicked element when building the selector for the element you want to change:

$('#ONE, #TWO, #THREE').live('click', function () {
    $('.hide').css('display', 'none');
    $('#b-' + this.id).css('display', 'block');
    // ^^^^^^^^^^^^^^
});

The initial selector ("#ONE, #TWO, #THREE") can probably be better written by giving all of those elements the same class attribute, and then using .the-class.

There may also be a structural approach, but as you haven't quoted your HTML, it's impossible to say.


Side note: The live function is not only deprecated, but actually removed from recent vesrions of jQuery. Here's the up-to-date equivalent:

$(document).on('click', '#ONE, #TWO, #THREE', function () {
    $('.hide').css('display', 'none');
    $('#b-' + this.id).css('display', 'block');
    // ^^^^^^^^^^^^^^
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875