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?
Don’t use setAttribute to set listeners, not all browsers allow that. Much better to either set the property directly:
or use addEventListener:
If you need to pass a parameter, then:
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.