Sunday, February 1, 2009

Browser compatability issues: With Dropdowns

The biggest problem in design of web pages is that styles applied for the pages won’t behave ‘same’ in different browsers. As a result an application that is developed for one browser might not work as expected in other browsers. This is due to the design/development of the browsers itself. But a job of good web designer lies in finding an effective solution for the problem at hand and not to get bogged down by the browser limitations. Recently I came across such an issue with the HTML dropdowns (List Boxes). When the width of a dropdown (DD) is fixed and the content length is more than the DD width, the content can’t be seen fully in IE6&IE7 but works perfectly well in Firefox. I.e. In Firefox the content gets adjusted keeping the width of the DD same, whereas in IE the content gets cut.

Here is one of the solutions to overcome such problem with Dropdowns

C# Code to add events on server side:

ddlList.Attributes.Add("onactivate", "maxWidth(this);");
ddlList.Attributes.Add("ondeactivate", "restoreWidth(this);");

Javascript code:

//This method will calculate the width dynamically based on the largest data in select options
//The maximum width will be assigned to dropdown

//The width will be changed only when the cursor is focused on dropdown
function maxWidth(mySelect)
{
var maxlength = 0;
for (var i=0; i<mySelect.options.length;i++)
{
if (mySelect[i].text.length > maxlength)
{
maxlength = mySelect[i].text.length;
}
}

mySelect.style.width = maxlength * 7;
mySelect.focus();
}

//This method is to restore to original width onblur of dropdown
function restoreWidth(mySelect)
{
mySelect.style.width="90px";
}