简体   繁体   中英

jQuery - Click Section to Hide but ignore when Inner Section Clicked

$(document).ready(function() {
  var $inners = $('.workSect .innerSect');
  $(".workSect").click(function() {
    var $inner = $(this).find('.innerSect'),
      visible = $inner.is(':visible');
    $inner.css({
      'visibility': visible ? 'hidden' : 'visible',
      'display': visible ? 'none' : 'block'
    });
    $inners.not($inner).hide();
  });
});

I have this code. It reveals and hides an inner section when the outer section is clicked. The inner section with class "innerSect" resides inside the outer section with class "outerSect"

The code works as desires except for one thing. When the inner section is clicked on it closes up. Which it's technically supposed to do since the inner section is inside the outer section and clicking on the outer section is what opens and closes the inner section.

What I would like is to have it ignore the inner section when clicked on. If it at possible. Maybe making a list instead of sections? Here is the JSFiddle.

You can check if the event target ( the element you've clicked on ) has a parent that has the .innerSect class, or if the target itself is .innerSect;

You can do it with jQuery closest() method:

var $target = $(event.target);
if($target.closest('.innerSect').length){
  return false;
}

Here is a fiddle: https://jsfiddle.net/zvjpoqyx/1/

However, in your case, you can just listen for clicks over the h2 elements.

Something like this should do it:

$('.workSect').click(function(event){
  if(!$('.innerSect').has($(event.target))){
    // closing code
  }
  else {
    // don't close
  }
});

This should do it:

$(document).ready(function() {
    var $inners = $('.workSect .innerSect');
    $(".workSect").click(function(e) {
        if( !$(e.target).closest('.workSect,.innerSect').is('.innerSect') ) {
            var $inner = $(this).find('.innerSect'),
                visible = $inner.is(':visible');
            $inner.css({
                'visibility': visible ? 'hidden' : 'visible',
                'display': visible ? 'none' : 'block'
            });
            $inners.not($inner).hide();
        }
    });
 });

DEMO

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