2

I have a piece of javascript is meant to add an onclick event to a div.

The div looks like this:

<div id="deck0" class="deck"></div>

And my javascript has:

var i = 1;
document.getElementById('deck0').SetAttribute("onclick", "begin("+i+")");   

But I get this error:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'SetAttribute' 

Am I doing it right, or is what I am trying to achieve not possible?

TRiG
  • 10,148
  • 7
  • 57
  • 107
Sir
  • 8,135
  • 17
  • 83
  • 146

4 Answers4

8

Don't use setAttribute to set listeners, not all browsers allow that. Much better to either set the property directly:

document.getElementById('deck0').onclick = begin;

or use addEventListener:

document.getElementById('deck0').addEventListener('click', begin, false);

If you need to pass a parameter, then:

document.getElementById('deck0').onclick = function() {begin(i);};

similarly for addEventListener.

Note that earlier versions of IE don't support addEventListener so you will need a cross–browser function to feature test for support. Where lacking, test for attachEvent and fall back to the direct property method. Search for "addEvent" functions, there are plenty of examples.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • 1
    Setting the onclick property is part of DOM 0, so it works in every browser that supports javascript, right back to Navigator 2 and IE 3. Setting the property is great if you only have one listener (which is the vast majority of cases), you need to be a little more clever when adding multiple listeners. – RobG Jul 25 '12 at 22:33
  • Okay thanks RobG :) Also if im adding an onclick via html method
    does that work the same way or is that the attribute method with limited support?
    – Sir Jul 25 '12 at 22:34
  • Setting inline listeners (i.e. the attribute in the markup) is fine and supported everywhere, just keep them concise. – RobG Jul 25 '12 at 22:35
  • here's an example of the cross-browser way for adding an event listener: http://stackoverflow.com/a/1724445/56829 – Omer Bokhari Jul 25 '12 at 22:36
4

Javascript is case-sensitive.
That should be setAttribute.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Javascript is case-sensitive, you'd need to write it lowercase.

Apart from that, to set event listeners no attributes should be used. This would need a string to be evaluated each time - you can do better from a script. Instead, assign a function to the onclick property:

document.getElementById('deck0').onclick = function(event) {
    begin(1);
};

Advanced event registration would be even better, but is more complex because Microsoft lacks supporting the standard.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

There are other ways to associate a function to the onclick event :

function deck0_onclick() {
    begin(i);
}

document.getElementById('deck0').onclick = deck0_onclick;

Or directly :

document.getElementById('deck0').onclick = function() {begin(i);}
Dalmas
  • 26,409
  • 9
  • 67
  • 80