Search code examples
jquerytogglechildren

Toggle show hide others using child or compound, not parent?


How to get toggle show hide from click of children or compound, not the click on parent?

I want to toggle Image A when click on Thumbnail A, not from the click of entire div. Thanks.

HTML

<div>
  <dl>
    <dt>Thumbnail A</dt>
    <dd>Name A</dd>
    <dd>Price A</dd>
  </dl>

  <ul class="details">
    <li>Image A</li>
  </ul>
</div>

jQuery

$(document).ready(function(){
  $('div').click(function() {
    var then = $(".details", this)
    $(then).toggle();
    $(".details:visible").not(then).hide();
  });
});

The answers given from the like of Maverick, David Thomas, j08691 and Tushar Gupta are pretty valid one using parent.siblings, but originally I've tried using compound like this:

$('div dl dt').click(function(){ 

But it wont work. I reckoned it has something to do with the var.

But please bear in mind I really need that, the toggle close when other toggle open and close itself when click on 'Thumbnail A' and so on, whic is dt, not div.

The compound alone work fine as it is but its now what I want to achieve. Here goes the original one.

Fiddle

http://jsfiddle.net/pandaktuai/v46zA/

And here with the mess up variable that achieve what I need but, the click can only select the most outer element, which is parent, (div).

Fiddle

http://jsfiddle.net/pandaktuai/Jeb86/

I hope I've shown my minimal understanding of this problem and much thanks if you all can lend me a hand.Thanks.


Solution

  • Simply modefy your js to this

    $(document).ready(function(){
    $('dt').click(function(){
    
     var then = $(this).parent().siblings(".details");
     $(then).toggle();
     $(".details:visible").not(then).hide();
    });
    
    });
    

    Example: http://jsfiddle.net/Jeb86/1/