I am using Jquery 2.1.0. I have injected some elements to the DOM (containing label) into a div element. I am using the following JavaScript to handle click event on all labels but it is completely dead and not responding. I checked and Jquery is loaded.
$('label').on("click", function () {
var ul = $(this).parent().children("ul:first");
if (ul.is(':visible')) {
ul.css({ "display": "none" });
}
else {
ul.css({ "display": "block" });
}
});
I used developer tools in IE 10 and debugged the code. When I hit F5 it goes to my break point (on first line of my code) but when I click a label nothing happens and no errors.
This will only assign the event handler to
labelelements which exist initially on the page:To catch elements which are added later, you need to assign the event handler to a common parent element (which isn't added/removed during the life of the page) and filter the source elements, like this:
Note that there are two selectors:
document'label'The first, which is the target of the event handler, is only evaluated once when the page loads (or when this line of code is evaluated, which is generally when the page loads). This attaches the handler to the
documentobject. Since all events "bubble up" to parent elements, this will catch all click events on the page (unless propagation is explicitly stopped, of course).The second, which is the "filter" for the
.on()method's handler, is evaluated any time an event is caught by this handler. It filters out the elements which originated theclickevent so that the handler is executed only for those which match the filter.I've actually recently blogged about this very subject.