1

I have a div main-wrap and an image in it.

I want to hide main-wrap when click on it. But when you click on image that is inside main-wrap I don't want to do anything. Right now I have this non-working code. When I click on image main-wrap still hides. (hidden is my class .hidden {display:none})

<div class="main-wrap" >
    <div class="photo-wrap">
        <img style="cursor:default;"  onclick = "return false;" class="img img-responsive" src = "/stat_photo/1.jpg"/>

    </div>
</div>

And I have this code

 $(document).ready(function() {
   $('.main-wrap').click(function(){$('.main-wrap').addClass('hidden')});
 });
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
user2950593
  • 9,233
  • 15
  • 67
  • 131

3 Answers3

1

I ended up with this code

$('.main-wrap').on('click', function(e) {
                    $('.main-wrap').addClass('hidden');
                }).on('click', 'img', function(e) {
                    // clicked on descendant div
                    e.stopPropagation();
});

which is taken from here How to have click event ONLY fire on parent DIV, not children? (the accepted answer didn't work though)

Community
  • 1
  • 1
user2950593
  • 9,233
  • 15
  • 67
  • 131
1
$('.main-wrap').click(function(e) {
   $(this).addClass('hidden');
}).on('click', 'img', function(e) {
  return false;
});

https://jsfiddle.net/bfwsqxko/1/

I added a click event, which extends with an exceptional click on image, which is set to return false;

halfer
  • 19,824
  • 17
  • 99
  • 186
ameenulla0007
  • 2,663
  • 1
  • 12
  • 15
-1

Better add an id of the image. Then replace .img with #yourid

  $(document).ready(function() {
          $('.main-wrap').not('.img').click(function(){$('.main-wrap').addClass('hidden')});
        });
Mir Gulam Sarwar
  • 2,588
  • 2
  • 25
  • 39