Date-picker Next click event

I needed to preform a event for the next button on the jQuery date-picker and got what I needed from this answer:

jquery datepicker adding event to next and previous button

But what I don't understand is why:

$(document).on('click', '.ui-datepicker-next', function() {
  // Preform event
};

Works but:

$(".ui-datepicker-next").on('click', function() {
  // Preform event
};

Doesn't work, in my case after two clicks?

Answers


This is called event delegation, and it is used when items are added to the DOM after the DOM has already been rendered.

The problem is that the click event is not bound to the desired element, because that element will later be injected into the DOM, so it does not yet exist. So jQuery must bind the click event to an element that actually exists at the time the DOM is rendered, and use event delegation (bubbling) to trap the event once the element is injected into the DOM.

Therefore, you need not use $(document) as your anchor, but you do need to use an element that is present when the DOM is rendered.

However, it is helpful to begin by using $(document).on and getting the code working, and then (once working) you can further narrow down the element you will use to trap the event.

Further reading:

https://davidwalsh.name/event-delegate

https://learn.jquery.com/events/event-delegation/


From the jQuery API docs:

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, you can use delegated events to avoid the need to frequently attach and remove event handlers.

In the first case, the handler is attached to the document which is guaranteed to be present. The selector then ensures the handler is only triggered when you click on .ui-datepicker-next.

However, in the second, there is no object available to attach the handler to, because the .ui-datepicker-next isn't present in the DOM at the time the handler is registered.


Need Your Help

Background (canvas) color disappears when rendering multi-mesh object in WebGL

javascript webgl

I'm currently learning WebGL, and I try to render an object with 2 separate meshes (a cube and a pyramid). To represent the object in WebGL, I use a multi-dimensional array like this:

Optimization report from gcc's pgo

linux gcc optimization pgo

I can see that gcc's PGO (profile guided optimization) works fine with my application (~15% faster execution). I'm using '-fprofile-generate' and then '-fprofile-use'. But is there any way to gener...