The jQuery selector selects the DOM elements, then applies a click handler to them. It does not overestimate the selector after changing classes in the element.
You probably want delegate()
/ on()
from jQuery to dynamically change the handler that starts when an element is clicked. The delegate works with event bubbles and handles the click and evaluates whether the source of the click matches the selector (during the click), and not to .click()
, which attaches the handler directly, once (during the loading page or whenever the code was executed )
Another solution is to change the handler, either by evaluating which class is in the existing element, or using toggleClass()
, which will check the class and then invert it.
$(".icon-minus, .icon-plus").click(function() { var $this = $(this); if ($this.hasClass("icon-plus")) { $this.removeClass("icon-plus").addClass("icon-minus"); return; } if ($this.hasClass("icon-minus")) { $this.removeClass("icon-minus").addClass("icon-plus"); return; } });
This method will be a little faster than using on()
/ delegate()
, because it is processed in the root handler and not sparged and checked later. It is also not subject to any interruption in the bladder. (i.e. event.stopPropagation()
)
Arena source share