views:

23

answers:

4

I am trying to set an event in JavaScript but it is not really working. I am pretty sure I am doing it correctly too.

// in index.htm:
function foo() {
  // Load gets code from a php file via ajax
  document.getElementById('div').innerHTML = load('phppage.php');
  document.getElementById('element').onClick = func;
}

// in lib.js:
function func() { alert('Working'); }

Unfortunately... it never alerts 'Working'. I have Google Chrome and I even inspected the element in the developer tools and found that the onClick property was infact func()... I don't understand why this wont work.

I do have extensive use of ajax. The element 'element' is actually loaded with ajax

+4  A: 

Try changing it to "onclick"

Matthew Abbott
javascript function names are case-sensitive, so +1 for you!
Mike Sherov
Thank you! this worked.
Alan
@Mike it's not about function names, see my answer...
galambalazs
@glambalazas, right, it's a property, not a function name. My mistake.
Mike Sherov
happens to everyone :)
galambalazs
A: 

I think the onclick property is lowercase. However, you should use event attaching methods.

element.addEventListener('click',func);

(and attachEvent for Internet Explorer)

Jan Kuča
A: 

Of course, there are plenty of frameworks out there to handle the cross browser issues for doing this, such as:

ExtJS

JQuery

Evan Trimboli
like changing a character? Oh I'm sure there are plenty of them.. It has nothing to do with browsers. Case-sensitivity is a part of the language.
galambalazs
What on Earth are you talking about? Everyone knows that using inline handlers is poor practice (http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/)Heck, you even advocate the same thing:http://stackoverflow.com/questions/3142710/inline-styles-vs-classes/3142741#3142741Frameworks abstract away the differences in the event models, for example shared/singleton event object or the difference between addEventListener and attachEvent. Seems you have something stuck in your behind ;)
Evan Trimboli
+1  A: 

HTML attributes are not, but javascript properties are case-sensitive. You need to use onclick to set the event handler.

galambalazs