0

Im trying to rewrite the following function for event delegation:

$("ul > li.closed").click(function (e) {
    if (e.target === this) {
        var li = $(this).closest('li');
        li.find(' > ul').slideToggle('fast');
        $(this).toggleClass("closed open");
    }
});

All the other functions I've rewritten run perfectly, but this one doesn't. Here is what I wrote:

$(document).on("click", "ul > li.closed", function (e) {
    if (e.target === this) {
        var li = $(this).closest('li');
        li.find(' > ul').slideToggle('fast');
        $(this).toggleClass("closed open");
    }
});

As you can see, I didn't really change a lot. The ul opens, but doesn't close anymore. Where is my mistake?

sqe
  • 1,656
  • 4
  • 21
  • 38

1 Answers1

3

The problem is once the li is opened, the class closed is removed and open is added, which means the the selector li.closed does not match

In the case of event delegation the selectors are evaluated lazily, but in case of normal event handling the handlers are registered to the target element at the time of the event registration so at that time which ever element had the class closed will get the handler

$(document).on("click", "ul > li:has(ul)", function (e) {
    var li = $(this).toggleClass("closed open");
    li.children('ul').slideToggle('fast');
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531