Reputation: 395
I'm using addClass() to add .expanded to an element on click. I then don't want another block of code to match that element anymore. I'm using a combination of .not() and .on() to try and get jQuery to notice the newly added class, but not having much luck - the handler I've written goes something like this:
$(".person").not("expanded").on({
mouseleave:...
});
Though obviously my .on() syntax isn't correct above, how can I utilise .not() with newly added classnames?
Upvotes: 0
Views: 148
Reputation: 7427
If you want live event, you can try something like this:
$(document).on('mouseleave','.person:not(.expanded)',function(){
...
})
The selector '.person:not(.expanded)'
will be used to filter the event.
If you used $('.person:not(.expanded)').on('mouseleave',function() { ...}
, it will attached the event handler only to the selected elements at this moment. If you changed expanded
class of an element, it will not be updated.
Better than document
you should attach the delegate to the container of your person elements (for performance reason). See on
documentation.
Upvotes: 3
Reputation: 4291
You can also remove the event handler from the desired element:
$("#removeHandlerFromMe").unbind('mouseleave')
Upvotes: 0
Reputation: 30666
Well, technically jQuery will not notice when an element is added or a class name is removed.
Event delegation works this way: you bind the event handlers to a parent (up to the document if needed). .on()
will use the selector parameter to execute the event handlers selectively to the "selector" parameter (if provided).
$("#someparent").on('mouseleave', '.person:not(.expanded)', function() {
...
});
The event "mouseleave" will bubble up to the element #someparent
and the target of the event (basically the element from which the event was triggered will be checked upon the provided selector .person:not(.expanded)
. If it matches, the event handler is executed.
Note that you can delegate to the document but it is better to delegation as close as possible to event targets.
Upvotes: 0
Reputation: 337560
You missed the .
on the not()
selector:
$(".person").not(".expanded").on('mouseleave', function() {
// code...
});
Upvotes: 0