user1354269
user1354269

Reputation: 35

jquery, on click anywhere inside div except certain child

I've got the following html

<div id="parent">
   <div id="window"><!-- contents of window ---></div>
</div>

Parent is 100% width with padding top and bottom and Window is centered inside it with a width of 600px.

What I need to figure out is a jquery selector which will trigger when the user clicks anywhere that is inside of Parent but outside of Window

Upvotes: 2

Views: 2414

Answers (3)

Daniel Ward
Daniel Ward

Reputation: 165

you can try this way

$('#parent').not("#window").on('click', function (e) {
    //do stuff
});

Upvotes: 0

nullability
nullability

Reputation: 10675

You can bind a click handler to #parent and then prevent propagation of clicks from #window. This allows you to have additional nested content inside of #parent without messing around with lists of the event targets.

$("#window").on("click", function(e) {
    e.stopPropagation();
});
$("#parent").on("click", function(e) {
    // Do your thing
});

See a demo here: http://jsfiddle.net/4kGJX/

Upvotes: 2

Anton
Anton

Reputation: 32591

Check if the target has id parent

$('#parent').on('click', function (e) {
    if (e.target.id == "parent") {
        //code for clicking outside window but inside parent
    }
});

DEMO

Upvotes: 5

Related Questions