brinch
brinch

Reputation: 2614

JQuery selector in event handler

Suppose I have this markup with a div and three child divs:

<div class='all'>
   <div class='x'>Hello from x div</div>
   <div class='y'>Hello from y div</div>
   <div class='z'>Hello from z div</div>
</div>

With my event handler I take care of when the user clicks somewhere in the div with class x.

$('.all').on('click', '.x', function (e) {
   alert('You clicked inside the x div')
});

Now comes my question. Can I write an event handler that responds to everything not coming from a click on the class x? Something like:

$('.all') * .not. * on('click', '.x', function (e) {
   alert('You clicked inside something different from the x div')
});

Upvotes: 1

Views: 31

Answers (2)

Weafs.py
Weafs.py

Reputation: 22992

Use :not() selector.

$('.all').on('click', ':not(.x)', function (e) {
   alert('You clicked inside something different from the x div')
});

$('.all').on('click', ':not(.x)', function (e) {
   alert('You clicked inside something different from the x div')
});
<div class='all'>
   <div class='x'>Hello from x div</div>
   <div class='y'>Hello from y div</div>
   <div class='z'>Hello from z div</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Upvotes: 1

Dave
Dave

Reputation: 10924

Yes, you can use the jQuery :not selector

$('.all').on('click', ':not(.x)', function (e) {
   alert('You clicked inside something different from the x div')
});

Upvotes: 3

Related Questions