5

I am trying to apply an onClick event to an array of elements in a document, like this:

for (var i = 0; i < myElems.length; i++)
     myElems[i].onClick = "someFunction(this)";

The code is placed inside of an init() function for the onLoad event of the body tag. I notice that when the document loads, the functions wont work.

I've noticed, that if I add an alert() to tell me if the function is the problem:

for (var i = 0; i < myElems.length; i++)
     myElems[i].onClick = "alert('It worked!')";

The document will load and perform the alert for all of the elements, without ever taking into consideration whether or not I actually clicked the element.

What am I doing wrong?

1
  • how are you calling the init function? Commented Sep 19, 2012 at 15:47

2 Answers 2

3

You need to assign the 'onclick' handler to a function:

for (var i = 0; i < myElems.length; i++)
     myElems[i].onclick = function() { someFunction(this);};

Assigning your 'alert' call directly will fire it (as you're seeing). What you want to do is assign your handler to a function that will be called when the event is fired.

Sign up to request clarification or add additional context in comments.

3 Comments

What @David Hoerster is saying is that you were assigning your onClick handler to a string, not the function itself.
Well, I feel silly. The handler works like a charm. I also noticed the comments about the method being "onclick" rather than "onClick." Thank you all.
@user1257262 Glad to be of help. Don't forget to mark an answer as the correct one, too. It will help your accepted answer rate and will help encourage more answers to future questions. Good luck!!
2

The property name is onclick.

onClick even though being valid HTML, does not exist in JS as it is case-sensitive.

Also you have to assign it a function reference or expression as David answered (+1).

Fiddle

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.