Chris Cummings
Chris Cummings

Reputation: 1548

Show only child div, hide all others

I'm a bit new to jQuery but I have the following:

<div class="team-member">
   <p>John Doe</p>
   <div class="team-member-text"Lorem Ipsum</div>
</div>
...several others...
   <div class="team-member">
   <p>Jane Doe</p>
   <div class="team-member-text"Lorem Ipsum</div>
</div>

I have the team-member-text divs all set to display:none.When user clicks on a team-member div, I want to expand that child team-member-text div and hide any open team-member-text divs on the page.

I have this working EXCEPT for the hide part. This is what I have.

jQuery( ".team-member" ).click(function() {
    jQuery('.team-member-text').not(this).hide();  //hide everything that isn't this one
    jQuery(this).find(".team-member-text").show( "slow", function() { 
       //toggle this one
    }); 
});

When you click again it hides then redisplays.

I found similar questions, but they didn't seem to be exactly the same.

Upvotes: 0

Views: 372

Answers (2)

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4588

You can write like this way also.

$(document).ready(function(){
     $(".team-member").click(function() {
         $("div.team-member-text").not($(this).find("div.team-member-text")).hide();
         $(this).find("div.team-member-text").show();
         //or
         $(this).siblings("div.team-member").find("div.team-member-text")).hide();    
     });
});

A little bit of explanation for you


On clicking team-member div I am checking for all team-member-text div but which is not current one's child and hiding them.

Next I am showing the current one's child.

Another way you can do is to check all sibling div team-member and find their children to hide them.

Upvotes: 0

adeneo
adeneo

Reputation: 318182

The problem is that this is not the .team-member-text element, but the .team-member element.

jQuery(function($) {

    $( ".team-member" ).on('click', function() {

        var thisOne = $(this).find(".team-member-text");

        $('.team-member-text').not(thisOne).hide();

        thisOne.show( "slow", function() {  });

    });
});

Upvotes: 2

Related Questions