JQuery toggle - close everything except this

I found this code (jQuery):

$('.toggle').click(function() { $('.container').eq($(this).index()).toggle('fast'); }); 

This is my HTML:

 <h4 class="toggle">Title1</h4> <h4 class="toggle">Title2</h4> <h4 class="toggle">Title3</h4> <div class="container">Content1</div> <div class="container">Content2</div> <div class="container">Content3</div> 

CSS

 .container { display: none; } 

I can switch what I want with him.

Problem

When I click on the toggle class, I want to close all open container classes, but not the current container class (because it needs to be switched).

The current container class should switch. This means that all elements can be closed, BUT ONLY ONE can be opened at the same time.

I tried to just hide jQuery before the script, but this makes it impossible to close the container class (because when switching hide show equally).

Guess the code to hide all .container except this

+4
source share
3 answers

Using David's answer as a starting point, we can use .siblings to accomplish what you want:

 $('.toggle').click(function() { var index = $(this).index(); $('.container').eq(index).toggle().siblings('.container').hide(); }); 

See: http://www.jsfiddle.net/85zCp/


As an aside, you can use JavaScript to hide all elements initially instead of CSS, because users with JavaScript disabled will not be able to see any content if you use CSS to hide them. In addition, you probably want each h4 header in front of the content, and not together, as you are doing right now.

+3
source

$('.toggle').click(function () { $('.container').hide('fast'); $('.container').eq($(this).index()).show('fast'); });

I don’t know for sure, but I think this is what you are looking for ...

Greeting...

+1
source

This is a little verbose, but its use should be fairly obvious:

 $('.toggle').click( function(){ var index = $(this).index(); $('.container').hide().eq(index).show(); }); 

JS Fiddle demo .

+1
source

Source: https://habr.com/ru/post/1335068/


All Articles