lowe_22
lowe_22

Reputation: 395

Using .not with dynamically added classes in jQuery

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

Answers (4)

Benoît
Benoît

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

papaiatis
papaiatis

Reputation: 4291

You can also remove the event handler from the desired element:

$("#removeHandlerFromMe").unbind('mouseleave')

Upvotes: 0

Didier Ghys
Didier Ghys

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

Rory McCrossan
Rory McCrossan

Reputation: 337560

You missed the . on the not() selector:

$(".person").not(".expanded").on('mouseleave', function() {
    // code...
});

Upvotes: 0

Related Questions