27

I was playing around with JavaScript in FireFox, and hit a problem that is illustrated in the following example:

<HEAD>
<script type="text/javascript">
function click()
{
    alert("click");
}

</script>
</HEAD>

<BODY>

<input type="radio" onclick="click()">
</BODY>

When I click on the radio button, nothing happens, and no errors (in Firebug)

If I change the name of the function to do_click, and change the onclick, then I get the alert.

So question is: what is happening? click does not appear to be a reserved word, or an existing symbol

5 Answers 5

38

Code within inline event handlers is scoped to the element, as if it was in a with block.

Therefore, within the onclick handler, the name click resolves to the element's click method.

This can be demonstrated by writing alert(nodeName) in the handler

3
  • Holy s*, I never knew this. Even behaves the same in IE. This seems so dangerous now.... Feb 5, 2010 at 1:56
  • 5
    There are so many properties hanging off of a DOM node. If a click handler was simply trying to set a global variable that happened to be named the same as one of the nodes properties (eg innerHTML), well.... crap. Feb 5, 2010 at 1:59
  • 7
    Yet another reason to not put any real code in an inline handler.
    – SLaks
    Feb 5, 2010 at 2:05
8

DOM elements have a native click() method.

The following will show that click is a native method:

<input type="radio" onclick="alert(click.toString())">

You can register your click function as the event handler as follows. Within the handler, this will refer to the HTML element.

<input type="radio" id="foo" >

function click()
{
    alert("click");
}
document.getElementById('foo').onclick = click;

There is an excellent series of articles about browser events at http://www.quirksmode.org/js/introevents.html

0

I think click() is a reserved procedure name, so you can't overwrite it. Explains why changing the name and nothing else gets it working.

1
  • "can't overwrite" is not correct. just that the target is different.
    – bryantsai
    Feb 5, 2010 at 1:53
0

I think the click() method in javascript simulates clicking the button. So this must be a sort of infinite loop...

Edited to add: Check out MSDN for documentation of the click method

0

'click' by itself is NOT a javascript reserved keyword outside the context of the inline event handler as Slaks answered.

That is to say the "click" method defined in the question is valid. Attaching the event handler 'externally' will work. E.g. using jQuery:

$('input').click(click);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.