Alan
Alan

Reputation: 2129

Setting an event with DOM javascript

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

Upvotes: 0

Views: 147

Answers (4)

gblazex
gblazex

Reputation: 50137

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

Upvotes: 1

Evan Trimboli
Evan Trimboli

Reputation: 30092

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

ExtJS

JQuery

Upvotes: -2

J. K.
J. K.

Reputation: 8368

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

element.addEventListener('click',func);

(and attachEvent for Internet Explorer)

Upvotes: 0

Matthew Abbott
Matthew Abbott

Reputation: 61617

Try changing it to "onclick"

Upvotes: 4

Related Questions