Austin
Austin

Reputation: 25

Call function on click unless click occurs on certain elements

When the user clicks on a modal, I'd like the modal to hide. I'm accomplishing this by using this code:

$(".modal").click(function(event){
  $('#myModal').modal('hide');
});    

However, .modal contains an img and p, and when the user clicks on these elements I don't want the modal to hide. What would be the best way to achieve this?

Thanks.

Upvotes: 1

Views: 54

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240928

Use $(event.target).is('.modal') to check if the clicked element is a modal.

$(".modal").on('click', function (event) {
    if ($(event.target).is('.modal')) {
        $('#myModal').modal('hide');
    }
});

Example Here

Upvotes: 1

Related Questions