Reputation:
I have a simple script that is trying to register a click on a button. However, I keep getting the error *element*.addEventListener
is not a function.
Can anyone explain what I'm doing wrong?
HTML
<div id="game">
<canvas id="gameScreen" width="550" height="500"></canvas>
<div id="output"><p></p></div>
<div id="controls">
<button id="north">North</button>
<button id="east">East</button>
<button id="west">West</button>
<button id="south">South</button>
</div>
</div>
JS
window.addEventListener("load", function(){
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var output = document.getElementById("output");
var outputText = output.querySelector("p");
var controls = document.getElementById("controls");
var directionButtons = controls.getElementsByTagName("button");
directionButtons.addEventListener("click", function(){
console.log(this);
})
})
Error
TypeError: directionButtons.addEventListener is not a function
Upvotes: 2
Views: 197
Reputation: 67505
The getElementsByTagName() method will return a list of nodes and you should loop through them and attach listener to every one :
function my_click(){
alert(this.id);
}
var directionButtons = controls.getElementsByTagName("button");
for(i=0; i<directionButtons.length; i++) {
directionButtons[i].addEventListener("click", my_click, false);
}
Hope this helps.
function my_click(){
alert(this.id);
}
var directionButtons = document.getElementsByTagName("button");
for(i=0; i<directionButtons.length; i++) {
directionButtons[i].addEventListener("click", my_click, false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='1'>Button 1</button>
<button id='2'>Button 2</button>
<button id='3'>Button 3</button>
<button id='4'>Button 4</button>
Upvotes: 4
Reputation: 15846
Variable directionButtons
is an array of multiple elements. You'll need to use loop here in order to add listeners.
window.addEventListener("load", function() {
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var output = document.getElementById("output");
var outputText = output.querySelector("p");
var controls = document.getElementById("controls");
var directionButtons = controls.getElementsByTagName("button");
for (i = 0; i < directionButtons.length; i++) {
directionButtons[i].addEventListener("click", function() {
console.log(this);
});
}
})
<div id="game">
<canvas id="gameScreen" width="550" height="500"></canvas>
<div id="output">
<p></p>
</div>
<div id="controls">
<button id="north">North</button>
<button id="east">East</button>
<button id="west">West</button>
<button id="south">South</button>
</div>
</div>
Upvotes: 1