Peter
Peter

Reputation: 732

Toggle this content and hide other content automatically using jQuery

The following jQuery code toggles the current content:

$(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class content
  $(".heading").click(function()
  {
    $(this).next(".content").slideToggle(500);
  });
});

Demo

I want to toggle (show/hide) the current content while hiding other items with the same class. For this, I added "$(".content").hide();" (see here.) But in this case, when I click an element which is currently shown again, it will not be toggled (hidden) but be shown again.

How can I handle it in this case?

Thanks for your help.

Upvotes: 2

Views: 217

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

Exclude the "current" one from the hide():

$(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class content
  $(".heading").click(function()
  {
    $(".content").not($(this).next(".content").slideToggle(500)).hide();
  });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/eK8X5/6829/

I realise this may look cryptic, so the long version (of the middle line) is:

 var $target = $(this).next(".content");
 $(".content").not($target).hide();
 $target.slideToggle(500)

Note: You will get a better visual effect if you slideUp() and not hide() the others:

e.g.

$(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class content
  $(".heading").click(function()
  {
    $(".content").not($(this).next(".content").slideToggle(500)).slideUp();
  });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/eK8X5/6832/

Upvotes: 3

Related Questions