I have a lot of pages that have buttons and I wanted to have mouse over effect without setting onmouseover and onmouseout in the html source. The best, of course, would be to use css style like a:hover, but I don't think this is going to work with older browsers. So, I used dynamically attaching to events for all buttons that have the same css class - 'inputButton' for example. I have two functions overBtn and outBtn that change the className of the button to 'inputButtonHover' on mouseover and back to 'inputButton' on mouseout. Here is the code:
<script type="text/javascript">
function overBtn( e )
{
var target = getTarget( e );
target.className = 'inputButtonHover';
}
function outBtn( e )
{
var target = getTarget( e );
target.className = 'inputButton';
}
function getTarget( e )
{
if ( window.event )
{
target = window.event.srcElement;
}
else if ( e )
{
target = e.target;
}
return target;
}
var buttons = document.getElementsByTagName( 'input' );
if( typeof window.addEventListener != 'undefined' )
{
//.. gecko, safari, konqueror and standard
window.addEventListener( 'load', MouseOverEffect, false );
}
else if( typeof document.addEventListener != 'undefined' )
{
//.. opera 7
document.addEventListener( 'load', MouseOverEffect, false );
}
else if( typeof window.attachEvent != 'undefined' )
{
//.. win/ie
window.attachEvent( 'onload', MouseOverEffect );
}
function MouseOverEffect()
{
for ( var i = 0; i < buttons.length; i++ )
{
if( ( ( buttons[i].type == 'submit' ) ( buttons[i].type == 'button' ) ) && ( buttons[i].className == 'inputButton' ) )
{
if ( buttons[i].addEventListener )
{
buttons[i].addEventListener( "mouseover", overBtn, false );
buttons[i].addEventListener( "mouseout", outBtn, false );
}
else if ( buttons[i].attachEvent )
{
buttons[i].attachEvent( "onmouseover", overBtn );
buttons[i].attachEvent( "onmouseout", outBtn );
}
else
{
buttons[i].onmouseover = overBtn;
buttons[i].onmouseout = outBtn;
}
}
}
}
</script>
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment