Tuesday, 1 April 2008

JavaScript - Hover effect

var _elementID;
var _xOffset = 15;
var _yOffset = 15;

function GetMouseX( event )
{
if ( !event )
{
event = window.event;
}

if ( event.pageX )
{
return event.pageX;
}
else if ( event.clientX )
{
return event.clientX + ( document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft );
}
else
{
return 0;
}
}

function GetMouseY( event )
{
if ( !event )
{
event = window.event;
}

if ( event.pageY )
{
return event.pageY;
}
else if ( event.clientY )
{
return event.clientY + ( document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop );
}
else
{
return 0;
}
}

function Follow( event )
{
if ( document.getElementById )
{
var element = document.getElementById( _elementID );

if ( element != null )
{
var style = element.style;
style.left = ( parseInt( GetMouseX( event ) ) + _xOffset ) + 'px';
style.top = ( parseInt( GetMouseY( event ) ) + _yOffset ) + 'px';
style.visibility = 'visible';
}
}
}

function Show( elementID )
{
if ( document.getElementById )
{
_elementID = elementID;

document.onmousemove = Follow;
}
}

function Hide( elementID )
{
if ( document.getElementById )
{
_elementID = elementID;

var divStyle = document.getElementById( _elementID ).style;
divStyle.visibility = 'hidden';

document.onmousemove = '';
}
}

Example:

<div id="Hover" style="background-color: White; color: Black; padding: 5px; position: absolute; visibility: hidden;">Test</div>
<div onmouseover="javascript:Show( 'Hover' )" onmouseout="javascript:Hide( 'Hover' )" style="background-color: Red; height: 100px; width: 100px;"></div>

4 comments:

Anonymous said...

This worked perfectly, great post!

GreyWolf said...

Nice, this script works nicely, I was able to implement it into my web page with ease.

Ali said...

Brilliant, thanks!

Anonymous said...

Dude you rock, this is exactly what i was looking for.