Good Sunday morning!
After fiddling around with some JavaScript this weekend, I finally wrote my first script. It is a Tooltip generator. It works great in FF 3 + 3.5, IE 6 + 7, Safari 4, Chrome 2 + 3, and Opera 9 + 10.
Before putting my new code into production, I thought I’d ask if you see any glaring problems — or maybe it’s perfect as-is? (Lol)
JSLint.com reports:
Error:
Problem at line 10 character 15: 'e' is already defined.
var e = window.event;
Implied global: window 10, document 19,20,22,24,33,35,41,43,49,55
Here is my code (apologies in advance if you don’t like my code style):
function getmouseposition( e )
{
var offx = 22;
var offy = 14;
var posx = 0;
var posy = 0;
if ( !e )
{
var e = window.event;
}
if ( e.pageX || e.pageY )
{
posx = e.pageX;
posy = e.pageY;
}
else if ( e.clientX || e.clientY )
{
posx = e.clientX
+ document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY
+ document.body.scrollTop
+ document.documentElement.scrollTop;
}
if ( document.getElementById )
{
var tooltip = document.getElementById( 'tooltip' );
tooltip.style.left = ( posx + offx ) + 'px';
tooltip.style.top = ( posy + offy ) + 'px';
}
}
function tooltip_on( text )
{
if( !document.getElementById( 'tooltip' ) )
{
var span = document.createElement( 'span' );
span.id = 'tooltip';
span.style.display = 'none';
span.innerHTML = ' ';
document.body.appendChild( span );
}
var tooltip = document.getElementById( 'tooltip' );
tooltip.innerHTML = text;
tooltip.style.display = 'block';
tooltip.style.position = 'absolute';
document.onmouseover = getmouseposition;
// document.onmousemove = getmouseposition;
}
function tooltip_off()
{
document.getElementById( 'tooltip' ).style.display = 'none';
}
EDIT:
I’m also wondering, what does this line say (in layman’s terms ) in the getmouseposition function:
if ( document.getElementById )
That jslint error means that the variable
eis already defined within the scope of thegetmousepositionfunction by virtue of being an argument to said function. There is no need to redeclare it, so just remove thevarfrom that line.Second, explicitly accessing properties of the
windowanddocumentobjects is pretty standard. I wouldn’t change that part of your code. Not sure why jslint even mentions those lines.Very picky style police will complain about spaces just within parentheses:
And very very picky style dorks will tell you to use a single var declaration at the top of your function:
Lastly, most style-conscious javascript programmers will use camel case for functions, so
getMousePositioninstead ofgetmousepositionMy opinion is that, besides removing the
vardeclaration as I suggested at the top, your code is quite readable and decent style, as long as you stick to the format consistently.