Monday, October 27, 2008

Automatically ajust AjaxControlToolkit Calendar position on the page

Many Deveopers are puzzled by this issue. When we create an AjaxControlToolkit Calendar control on the page, if the Calendar control is closed to the bottom of page and there is no room to present the whole Calendar, the Calendar will be still popped up towards the bottom of page. We can only see a part of Calendar.

We hope that it can ajust position itself. If there is no room to present, it can popped up upwards.



The below codes will achieve it by making use of client event "OnClientShown".



<script type="text/javascript" language="javascript">
//$get('<%=TextBox1.ClientID %>').value=sender.get_selectedDate().localeFormat("MM/dd/yyyy");
function getTop(e)
{
var offset=e.offsetTop;
if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
return offset;
}


function onCalendarShown(sender,args)
{
var calendar= $find('Calendar1');
var screenTop=null;
if(Sys.Browser.agent==Sys.Browser.InternetExplorer)
screenTop=document.documentElement.scrollTop;
else
screenTop=document.body.scrollTop;
var screenBottom=screenTop+document.documentElement.clientHeight;

if((getTop(calendar.get_element())+calendar.get_element().offsetHeight+calendar._height)>screenBottom)
{

calendar._popupDiv.style.top=getTop(calendar.get_element())-calendar._popupDiv.offsetHeight+'px';
}



}


</script>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<br /><br /><br /><br /><br /><br /><br /><br /><br />
<ajaxToolkit:CalendarExtender ID="calendar1" runat="Server" BehaviorID="Calendar1" TargetControlID="TextBox1" PopupPosition="BottomLeft" OnClientShown="onCalendarShown" />
<asp:TextBox ID="TextBox1" runat="server" autocomplete="off" ></asp:TextBox>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
</form>
</body>

1 comment:

Anonymous said...

Hi Vince,

Thanks for your great post. I have modified it slightly so that the Calendar does not only eppear at the bottom or top, but relative to how far down you are scrolled.

function getTop(e)
{
var offset=e.offsetTop;
if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
return offset;
}

function onCalendarShown(sender,args)
{
var calendar = sender; //$find('Calendar1');
var screenTop=null;

if(Sys.Browser.agent==Sys.Browser.InternetExplorer)
screenTop=document.documentElement.scrollTop;
else
screenTop = document.body.scrollTop;

var screenBottom=screenTop+document.documentElement.clientHeight;
var diff = (getTop(calendar.get_element()) + calendar.get_element().offsetHeight + calendar._height) - screenBottom + 30

if(diff > 0)
calendar._popupDiv.style.top = (getTop(calendar.get_element()) - diff) + 'px';
}

Thanks
Clive