[JS] Script fails to work when has the same name as DOM's element ID?

Hi,

This is actually JS question, but since there is no separate forum…

I think I found something strange. I have image (generated using CHTML::image) and jQuery script (added to view via registerScript) with a very simple animation. If generated code looks like this:


function blink(){$("#logo-img").show("scale", {percent: 100}, 700);}


<img id="logo-img" width="90" height="90" ondblclick="blink()" src="/www/gfx/_logo.png" alt="Logo" />

everything seems to be fine. But when I change function name to be the same as object ID:


function test(){$("#test").show("scale", {percent: 100}, 700);}


<img id="test" width="90" height="90" ondblclick="test()" src="/www/gfx/_logo.png" alt="Logo" />

I’m getting error: “test is not a function”.

The name test has nothing to do here, I tested the case with many different, even random-typed from keyboard. Whenever function name and ID it uses are the same I’m getting this error, and when they’re different – all is OK.

Seems to be a little bit strange. Isn’t?

In javascript the ID’s of DOM elements are fully qualified variable names and so are functions. So what you are doing (effectively):




test = function() { do stuff }


//insert your element in the DOM


test = document.getElementById('yourelement');



In other words you are overwriting test. Of course all of this assumes you are operating in the global scope.

Thanks, Luke Jurgs! That explains everything here…