Elgoog
Elgoog

Reputation: 2275

Set one element at a time as 'active'

The easiest way for me to explain the question is by you looking at my code at jsfiddle

each Div has only one link which once clicked sets the Div to active + shows a hidden Div within it. So when you click the link again it toggles the active style and hides the hidden Div. this is how I want it, but i am also wanting it so that if I click on another link and the previous Div is still set to active it will only set that Div(just clicked) as active and toggle the previous div.

I hope this makes sense if you need any more info let me know.

Also If you see a better way of coding this little piece of code, I would love suggestions.

Thanks.

Upvotes: 1

Views: 5921

Answers (2)

Alnitak
Alnitak

Reputation: 339816

If your markup guarantees that all of the related divs are siblings, this works (and without using any IDs or attributes):

$('.href').click(function (ev){
    ev.preventDefault();

    // find enclosing div
    var p = $(this).closest('div');

    // make this one active, and make others inactive
    $(p).addClass('active')
        .siblings('.active').removeClass('active').find('.hidden').hide();

   // and change the hidden div
    $(p).find('.hidden').toggle();
})

http://jsfiddle.net/alnitak/y8kys/

The middle line does the hard work - it ensures the outer div has the right class, that none of its siblings does, and that the hidden elements in every sibling are also hidden.

I put another version at http://jsfiddle.net/alnitak/ZfhbU/ which works when the enclosing divs aren't siblings.

Upvotes: 2

James Allardice
James Allardice

Reputation: 165971

Before showing the hidden div, you can check all of the other hidden div elements, hide them if necessary, and toggle the style on the parent div:

$('.hidden').each(function() {
    if($(this).is(":visible")) {
       $(this).hide("slow");
       $(this).parent().toggleClass("active");
    }
});

See an updated fiddle for an example.

Upvotes: 1

Related Questions