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?
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?
Share Improve this question edited Apr 3, 2015 at 11:08 TRiG 10.6k8 gold badges61 silver badges111 bronze badges asked Jul 25, 2012 at 22:22 SirSir 8,27717 gold badges88 silver badges154 bronze badges4 Answers
Reset to default 8Don'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.
Javascript is case-sensitive.
That should be setAttribute
.
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);}
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 plex because Microsoft lacks supporting the standard.