How to keep jquery ui datepicker in place (stick to the input control) while scrolling?

krul picture krul · May 17, 2012 · Viewed 17.3k times · Source

After reading a lot of on the subject I'm still in the dark about how to approach resolving the problem. To clarify problem, I want calendar to scroll altogether with input control associated and not to stay fixed at whatever screen position. Here is image with no scroll: (that is what I want to preserve on scroll as well) enter image description here

and here is image while scrolling : (that is not what I want)

enter image description here

Any tip would be greatly appreciated. UPDATE: Here is a link that closely portray the problem, I would like calendar to stick to the control while scrolling.

Answer

Prasenjit Kumar Nag picture Prasenjit Kumar Nag · May 17, 2012

I am not sure if your's one is a scrollable div, but the problem occurring here is jQuery UI date picker doesn't move with HTML content when inside a scrollable div.

Here is a fiddle which demo http://jsfiddle.net/joycse06/m6A5q/embedded/result/ demonstrating the problem. Click on input and try scrolling that div.

It's happening because jQuery UI create the calendar UI as position absolute relative to document or window not the container scrollable div. So when the scrollable div is scrolled main window's scrolling context isn't changed and hence the datepicker calendar doesn't follow other html element in that div.

So the solution can be to hide the calendar when that div is scrolled and it makes sense, if the input is not visible you can hide the datepicker calendar. So the updated code will be

var datePicker = $('#datepicker').datepicker();

$(".demo").scroll(function() {
  datePicker.datepicker('hide');
  $('#datepicker').blur();
});

$(window).resize(function() {
  datePicker.datepicker('hide');
  $('#datepicker').blur();
});

It will hide the date picker when container div or window is scrolled. here is a working fiddle http://jsfiddle.net/joycse06/m6A5q/2/

I am using the $('#datepicker').blur(); because when user scrolls .demo calendar hides but the input is still focused, so when he scrolls back he can become confused. So as I blur it he will have to click on the input again and date picker will show up.