Ned Batchelder
Ned Batchelder

Reputation: 375784

Using jQuery to only show one of a pair of elements

I have a number of message elements that come in pairs: If element A1 is shown, then A2 should be hidden, same for B1/B2, C1/C2, and so on. I have the jQuery code working, but it gets verbose:

if (conditionA) {
    $("#a1").show();
    $("#a2").hide();
else {
    $("#a1").hide();
    $("#a2").show();
}

if (conditionB) {
    $("#b1").show();
    $("#b2").hide();
else {
    $("#b1").hide();
    $("#b2").show();
}

//etc...

This seems cumbersome and mind-numbing. Is there a better way to encapsulate the notion that these elements are paired and should show/hide opposite each other? I've looked at toggle, but that isn't right.

Upvotes: 0

Views: 390

Answers (3)

Alex Barrett
Alex Barrett

Reputation: 16475

Actually toggle can help you here, if you make use of the optional switch parameter.

$("#a1").toggle(conditionA);
$("#a2").toggle(!conditionA);

$("#b1").toggle(conditionB);
$("#b2").toggle(!conditionB);

Upvotes: 3

Ned Batchelder
Ned Batchelder

Reputation: 375784

Here's what I ended up doing:

I organized the HTML to have the pair of elements paired under a new parent for naming purposes:

<p id="first_flap"><span class="flap">MsgA1</span><span class="flap">MsgA2</span></p>
<p id="second_flap"><span class="flap">MsgB1</span><span class="flap">MsgB2</span></p>

Each of the pair has class "flap" on it. Then I can write a function:

function flip_flap(sel, cond) {
    /* Find sel, then show flaps within it according to cond. */
    var flaps = jQuery(sel + ">.flap");
    var f0 = jQuery(flaps[0]);
    (cond ? f0.show() : f0.hide());
    var f1 = jQuery(flaps[1]);
    (cond ? f1.hide() : f1.show());
}

I liked the idea of using toggle(), but unfortunately, it doesn't work for inline elements, only block level, and I needed to use spans.

Then I can replace my original Javascript with:

flip_flap("#first_flap", conditionA);
flip_flap("#second_flap", conditionB);

Much more concise! Thanks.

Upvotes: 0

helloandre
helloandre

Reputation: 10721

I would organize your html so that you could use siblings() and toggle().

Upvotes: 0

Related Questions