Description
The library, codeapedia.mouse.js can be used to track the current mouse position and/or dynamically assign event handlers to the mouse events.
Code
/**
* @projectDescription Mouse library
*
* @author Ryan Estes http://www.codeapedia.com
* @version 0.2
*/
/**
* Create a new instance of coordinate
*
* @classDescription Defines a Cartesian coordinate
* @return {coordinate} Returns a new coordinate.
* @type {Object}
* @constructor
*/
var coordinate = function(pX,pY)
{
this.x = pX;
this.y = pY;
}
var mouse =
{
events :
{
onclick : 0x000000,
ondblclick : 0x000001,
onmouseover : 0x000010,
onmouseout : 0x000100,
onmousemove : 0x001000,
onmouseup : 0x010000,
onmousedown : 0x100000,
/**
* Assigns a mouse event to an object
* @return {void}
*/
register : function(pFunction,pObject,pEvent)
{
var e = pEvent;
var f = pFunction;
var o = pObject;
if(o == null || f == null)
{
return false;
}
if(o.length)
{
o = document.getElementById(o);
}
switch(e)
{
case mouse.events.onclick:
o.onclick = f;
break;
case mouse.events.ondblclick:
o.ondblclick = f;
break;
case mouse.events.onmouseover:
o.onmouseover = f;
break;
case mouse.events.onmouseout:
o.onmouseout = f;
break;
case mouse.events.onmousemove:
o.onmousemove = f;
break;
case mouse.events.onmouseup:
o.onmouseup = f;
break;
case mouse.events.onmousedown:
o.onmousedown = f;
break;
default:
throw "Invalid argument exception";
}
}
},
/**
* Gets the current mouse position
* @return {coordinate}
*/
getCoordinate : function(e)
{
var objCoord = new coordinate(0,0);
if(!e)
{
e = window.event;
}
if(e.pageX && e.pageY)
{
objCoord.x = e.pageX;
objCoord.y = e.pageY;
}
else if (e.clientX && e.clientY)
{
objCoord.x = e.clientX +
((document.documentElement.scrollLeft)?
document.documentElement.scrollLeft :
document.body.scrollLeft);
objCoord.y = e.clientY +
((document.documentElement.scrollTop)?
document.documentElement.scrollTop :
document.body.scrollTop);
}
return objCoord;
}
};
Example
<body>
<a id="lnk" href="javacsript:void(0)" >Link</a>
</body>
<script type="text/javascript" language="javascript" >
var f = function(event)
{
var evt = arguments[0];
var o = mouse.getCoordinate(evt);
alert(o.x);
alert(o.y);
}
mouse.events.register(f,"lnk",mouse.events.onclick);
</script>

0 comments:
Post a Comment