This question has already been answered:

There is a code

$(function() { $('html').click(function() { removeActiveMenuClass(); }); $( '.ibtn' ).click(function(e) { e.preventDefault(), e.stopPropagation(); removeActiveMenuClass(); $(this).children('.dropdown').addClass('open'); }); function removeActiveMenuClass(){ $('.ibtn').children('.dropdown').removeClass('open'); } }); 

He is a worker, but I still need to, when I click on the button again, the block toggleClass something like toggleClass , now the .open class .open not removed when you click again, I wanted to do something like https://trend-spb.ru/metro / rybackoe filter block.

Reported as a duplicate by Igor , Vadim Ovchinnikov , Community Spirit Jan 15 '17 at 1:41 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Somehow it is not clear question raised - Eugene Sukhodolskiy
  • one
    Well, can you do .toggleClass ('open') instead of addClass? - Orange_shadow
  • Tried, does not work. - Makissm
  • Thank you very much, the code on the link worked fine. - Makissm

1 answer 1

The whole problem is in the removeActiveMenuClass() function or how you use it. In this part of the code:

 $( '.ibtn' ).click(function(e) { e.preventDefault(), e.stopPropagation(); removeActiveMenuClass(); $(this).children('.dropdown').addClass('open'); }); 

When clicking on the .ibtn element, the standard behavior and further event transfer are removed first (the second is most likely superfluous, but that’s not the point). Next, the removeActiveMenuClass() function is removeActiveMenuClass() , which removes the open class from everyone (including the current one) .dropdown , and then adds the open class again. Therefore, for the toggleClass() method to toggleClass() you need to delete the open class for everyone but the current one.

Alternatively, you can use the .not method:

 $(function() { $(document).click(function() { removeActiveMenuClass(); }); $( '.ibtn' ).click(function(e) { e.preventDefault(), e.stopPropagation(); $('.ibtn').not(this).children('.dropdown').removeClass('open'); $(this).children('.dropdown').toggleClass('open'); }); function removeActiveMenuClass(){ $('.ibtn').children('.dropdown').removeClass('open'); } }); 
 .dropdown { display: none; } .dropdown.open { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" class="ibtn"> Click <div class="dropdown">I'm dropdown</div> </a> 

  • Thank you for responding, but I used the code from the link above, in your example, when you click on the opened block, it closes, i.e. class open is removed and does not even choose what you need in it. But thanks anyway! - Makissm