简体   繁体   中英

Only one Active class and Visible Div at a time

There are a bunch of div elements on the page.

I have a nested div inside of them.

I want to be able to add a class to the click ed element, and .show() the child div.

$('.container').on('click', function(){
    $(this).toggleClass('red').children('.insideItem').slideToggle();
});
  • I can click on it, it drops down.
  • Click again, it goes away.

So, now I need some method to removeClass() and slideUp() all of the other ones in the event of a click anywhere except the open div . Naturally, I tried something like this:

$('html').on('click', function(){
    $('.container').removeClass('red').children('div').slideUp();
});

Well, that just stops the effect from staying in the first place. I've read around on event.Propagation() but I've read that should be avoided if possible.

I'm trying to avoid using any more prebuilt plugins like accordion , as this should be a pretty straightforward thing to accomplish and I'd like to know a simple way to make it work.

Would anyone be able to show a quick example on this fiddle how to resolve this?

  • Show only one active div, and collapse all others if clicked off

https://jsfiddle.net/4x1Lsryp/

One way to go about it is to update your code with the following:

1) prevent the click on a square from bubbling up to the parent elements 2) make sure to reset the status of all the squares when a new click is made anywhere.

$('.container').on('click', function(){
  $this = $(this);
  $('.container').not($this).removeClass('red').children('div').slideUp();
  $this.toggleClass('red').children('div').slideToggle();
  return false;
});

See the updated JSfiddle here: https://jsfiddle.net/pdL0y0xz/

You need to combine your two approaches:

 for (var i = 0; i < 10; i++) { $('#wrap').append("<div class='container'>" + i + "<div class='insideDiv'>Inside Stuff</div></div>"); } $('.container').on('click', function() { var hadClassRed = $(this).hasClass('red'); $('.container').removeClass('red').children('div').slideUp(); if (!hadClassRed) { $(this).toggleClass('red').children('div').slideToggle(); } }); 
 .container { width: 200px; height: 200px; float: left; background: gray; margin: 1em; } .insideDiv { display: none; } .red { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrap"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM