jsfiddle.net/auggszet/ 

script itself

when the button is pressed to open, the block opens, when pressed again it should close, and it will close-open

I did it through the active class but still it doesn’t work out correctly. Please tell me what the troubles are.

2 answers 2

Why so much code, yet solved in 3 lines

 $(function() { $(this).on("click", "#open_but , #close_but", function() { $(this).closest("div#div").find("#cont").stop().slideToggle() }); }); 

https://jsfiddle.net/3cszmvy4/1/

  • Yes, you are right, I’m not so good about jq, but as in the original example, the block should also close when clicking on it is not his example @ soledar10 is very short, but it is designed for 1 block per page, but I need a few - Anton Postnov
  • Look at the example that I gave https://jsfiddle.net/3cszmvy4/1/ there just any number of blocks - Redr01d
  • "but as in my initial example, the block should also close when not clicking on it" until here is the working version of jsfiddle.net/auggszet/5 - Anton Postnov
  • then like this, also much shorter https://jsfiddle.net/3cszmvy4/2/ if you click outside the block, then all blocks are closed - Redr01d
  • I will honestly say, I almost don’t understand how it works) but when I click on the content the block closes, thanks, don’t bother with the topic, your example is cool but there are a few shortcomings besides the one mentioned - Anton Postnov

Finished version:

 $("#open_but").bind( 'click', function( e, display ){ var parent = $(this).parents('#div'); if ( display == undefined ) { var flag = $(parent).hasClass("active"); } else { var flag = ( display == 'hide' ) ? false : true; } if ( !flag ) { $(parent).addClass('active').find('#cont').fadeIn('fast'); } else { $(parent).removeClass('active').find('#cont').fadeOut('fast'); } }); $("#close_but").click(function(){ $("#open_but").trigger('click', { display: 'hide' } ) }) $(document).mouseup(function (e) { if ( $(e.target).attr("id") != 'open_but' ) { $("#open_but").trigger('click', { display: 'hide' } ) } }); 
 div > span,div div,div div span{padding:5px;border:1px solid #444;display:block;} div div{display:none;} div:hover,span:hover{border-color:#ddd;} 
 <div id="div"> <span id="open_but">открыть</span> <div id="cont"> контент <span id="close_but">закрыть</span> </div> </div> 

  • Alas, but not this, when I click outside the main parent, the block closes if it is open - Anton Postnov
  • one
    Well, because of him, he was hiding with you - the click was taken into account at any place, including when pressing the button. jsfiddle.net/40gd2r3e - with processing. - Idushii
  • @Idushii So what is the link in which the correct answer in the end? Please put the code from the link directly in response. Links have a rule to die off with time - Alexey Shimansky