Wednesday, November 29, 2006

Better to detect the browser features than detecting the browser

I have came across a code snippet on a famous WEB 2.0 product, Just have a look at it : ( I have copied this code from FF Javascript debugger console )

function getXY(e)
{

if(navigator.appVersion.match(/\bMSIE\b/))
{
return getXYIE(e);
}
else
{
return getXYMozilla(e);
}
}


function getXYMozilla(e)
{
xyArray = new Array(2);
var some_handler = document.getElementById("some_id");
xyArray[0] = e.layerX - some_handler.offsetLeft;
xyArray[1] = e.layerY - some_handler.offsetTop;
return xyArray;
}

function getXYIE(e)
{
xyArray = new Array(2);
xyArray[0] = e.offsetX;
xyArray[1] = e.offsetY;
return xyArray;
}


I think we can do the same functionality with the below code ( Without detecting the browser , but only detecting the browser features ). Just have a look into it :


function getXY(e)
{
return myCode(e);
}


function myCode(e)
{
xyArray = new Array(2);
var some_handler = document.getElementById("some_id");
alert(e.offsetX);
xyArray[0] = e.offsetX ? e.offsetX : (e.layerX - some_handler.offsetLeft);
xyArray[1] = e.offsetY ? e.offsetY : (e.layerY - some_handler.offsetTop);
return xyArray;
}

Open to suggestions.