[Javascript] Trouble with id

Nick Fitzsimons nick at nickfitz.co.uk
Tue Jun 5 07:33:40 CDT 2007


On 5 Jun 2007, at 04:13:51, Del Wegener wrote:

> This is the JavaScript function
> function toggle_visibility(id)
> {
>  var e = document.getElementById(id);
>  if(e.style.visibility != 'visible')
>   e.style.visibility = 'visible';
>  else
>   e.style.visibility = 'hidden';
> }
>
> This is the HTML which does the calling
> <a href="#"onMouseOver = toggle_visibility(104)>
> <img src="../../image/icon_toggle.jpg" width="22" height="22"  
> border="0"></a>
>  <span class = "hidden_hint" id=104>
>   Add -<img src="../images/sq_root_7.gif" align="absmiddle"> to  
> both sides
> of the equation.
> </span>
>
> This works fine when I use a number for the id.
> However I would prefer(reasons involve the rest of the page) to use  
> "hint4" for the ID
> When I use hint4 with or without quotes, the whole toggle fails.
> An ALERT inserted  in the function returns object for id when I use  
> hint4
> and returns the number when I use a number.

As others have pointed out, your markup is ill-formed, and it's a  
violation of the spec to use a numeric id:
<http://www.w3.org/TR/html4/types.html#type-name>

How are you using the id in your inline event handler? If you are using

onmouseover="toggleVisibility(hint4)"

then you are passing a reference to a global variable called hint4,  
which will normally evaluate to either undefined or an object (the  
DOM element having the id hint4, if one exists). You need to pass a  
string, as that is what document.getElementById expects to receive:

onmouseover="toggleVisibility('hint4')"

(note the single quotes around the argument.)

In your toggle routine, you are directly changing the visibility  
property; have you considered toggling the className instead? You  
already have class="hidden_hint" on the toggled element; try using:

e.className = (e.className == "" ? "hidden_hint" : "");

to replace the if...else construct.

It's also better if you don't associate event handlers with elements  
inline in your HTML; google around for the terms "unobtrusive  
javascript" and "dom scripting" to get an idea of the better  
techniques which have superseded the 1997 approach now that we no  
longer have to support Netscape 2.

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list