Home > Software engineering >  Append jQueryUI datepicker to div (wrong display position)
Append jQueryUI datepicker to div (wrong display position)

Time:10-08

I'm using jQueryUI datepicker on an input, and as default jQueryUI appends the #ui-datepicker-div to the body of the document.

The input in question is in a "popup" div on the screen, meaning any click outside of that div will close the "popup".

Because jQueryUI is appending the datepicker to the body, when I click on the datepicker the "popup" disappears... so I've tried moving it into the popup using the (currently) unaccepted answer on this question...

$("#myInput").datepicker({
  ...
  beforeShow: function() {
    $("#ui-datepicker-div").appendTo($("#myPopupDiv"));
  }
});

The problem is that jQueryUI then sets the top and left CSS style onthe #ui-datepicker-div based on a position relative to the body... but I need it to be relative to the "popup" div.

I've tried setting position:relative to #myPopupDiv. And I've also tried setting top and left as part of the beforeShow, but those values are immediately overwritten.

Is there anyway to make it position correctly?

Please see the following simple example, where the input is at 50px/100px, but the datepicker now appears at 100px/200px...

CodePudding user response:

The position of the singleton can be set with $.datepicker._pos = [x, y].

However, each time the datepicker dialog shows up, it sets the _pos to null and therefore recalculates the position at the subsequent use.

In your case, the following would set the position each time before opening.

$("input").datepicker({
    beforeShow: function() {
        $.datepicker._pos = [20, 0];
        $("#ui-datepicker-div").appendTo($("#myPopupDP"));
    }
});
  • Related