Deka87 Deka87 - 6 months ago 7
HTML Question

Failing to call action on the previously active item

In short, I have a list of items, one of which is set to

.active
:

<ul>
<li class="active"></li>
<li></li>
<li></li>
</ul>

$("li:not(.active)").click(function() {
$(this).addClass("active")
.siblings("li").removeClass("active");
});


https://jsfiddle.net/sasy0faL/

When you click one of the items that is not
.active
, the code should change its status and remove the
.active
class from other items.

To reproduce the issue, you need to click one of the inactive items (for example the 2nd one), then try to click on the previously active item (the 1st one) to make it active again. It will fail to do so, even though it is not active at the moment. Any ideas?

Answer

Currently what you are using is called a "direct" binding which will only attach to elements that exist on the page at the time your code makes the event binding call.

So, As per current implementation event handler is only attached with element which does't have the active class.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

$('ul').on('click', "li:not(.active)", function() {
  $(this).addClass("active")
    .siblings("li").removeClass("active");
});

jsFiddle

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Comments