Jeroen
Jeroen

Reputation: 167

how to find other divs with same classname and close them

i'd like to know what i should do to show only one div out of multiple divs with the same classname. If one is open and i click another, the one that is open should close, and the one that i clicked on should open.

HTML:

<div class="out">
    <div class="content"> <a>click here to learn more..</a>

    </div>
</div>
<div class="out">
    <div class="content"> <a>click here to learn more..</a>

    </div>
</div>
<div class="out">
    <div class="content"> <a>click here to learn more..</a>

    </div>
</div>

CSS:

.out {
    width:150px;
    height: 25px;
    background-color: green;
    float: left;
    margin-right:10px;
}
.open {
    border-bottom:5px solid peru;
    height: 150px;
}
.out.open .content {
    width:100%;
    height:100%;
}
a {
    display: none;
}
.open .content {
    display: block;
}
.open .content > a {
    color: white;
    text-decoration: underline;
    display: block;
}

JS:

$(document).ready(function () {
    $('.out').click(function () {
        $('.out').find('open').removeClass('open');
        $(this).addClass('open');
    });
});

I know the problem is in the jquery, but i have no clue of what i'm doing wrong.

Here's a fiddle too: http://jsfiddle.net/4hpgb/22/

Upvotes: 2

Views: 219

Answers (4)

codingrose
codingrose

Reputation: 15699

Write:

$('.out').click(function () {
    if(!($(this).hasClass('open'))){
        $('.out.open').removeClass('open');
    }
    $(this).addClass('open');
});

Updated fiddle here.

Upvotes: 2

Nouphal.M
Nouphal.M

Reputation: 6344

Close all the open divs first

$(document).ready(function () {
    $('.out').click(function () {
        $('.out').find('open').removeClass('open');
        $('.open').each(function(i,v){
             $(this).removeClass('open');
        });
        $(this).addClass('open');

    });
});

Demo here

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 15112

JSFIDDLE DEMO

$('.out').click(function () {
    $('.out').removeClass('open');
    $(this).toggleClass('open');
});

Upvotes: 2

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Just change this line:

$('.out').find('open').removeClass('open');

to this:

$('.out').removeClass('open');

It should work.

What is happening is that you're removing all classes open from all div.out, then adding class open to the current one.

Upvotes: 2

Related Questions