styke
styke

Reputation: 2174

Cannot attach Event listener to canvas?

I've got some very simple code that attempts to attach an event listener and call a function on mousemove, so that I can find the mouse position within a canvas element:

canvas = document.getElementsByTagName('canvas');
canvas.addEventListener('mousemove', on_canvas_move, false);

function on_canvas_move(ev) {
    var x = ev.clientX - canvas.offsetLeft;
    var y = ev.clientY - canvas.offsetTop;
    $('#status').html(x +', '+ y);
}   

However I get the error: Uncaught TypeError: Object # has no method 'addEventListener'

What exactly is going on here?

Upvotes: 1

Views: 4961

Answers (2)

jfriend00
jfriend00

Reputation: 707218

getElementsByTagName() returns a nodeList (like an array of DOM objects) so you need to designate which element in that nodeList you want to add the listener to.

And secondly, your event handler on_canvas_move() also has the same issue as canvas.offsetLeft would be trying to read the .offsetLeft property on the nodeList, not on the DOM element. That would give you an undefined value and trying to do math with undefined gives you NaN.

To add just one:

canvas = document.getElementsByTagName('canvas');
canvas[0].addEventListener('mousemove', on_canvas_move, false);

function on_canvas_move(ev) {
    var x = ev.clientX - this.offsetLeft;
    var y = ev.clientY - this.offsetTop;
    $('#status').html(x +', '+ y);
} 

Or, to add all of them:

canvas = document.getElementsByTagName('canvas');
for (var i = 0; i < canvas.length; i++) {
   canvas[i].addEventListener('mousemove', on_canvas_move, false);
}

function on_canvas_move(ev) {
    var x = ev.clientX - this.offsetLeft;
    var y = ev.clientY - this.offsetTop;
    $('#status').html(x +', '+ y);
} 

Upvotes: 2

moonwave99
moonwave99

Reputation: 22817

document.getElementsByTagName() returns you an array - you should either loop it and bind the listener, or point to the element you need:

document.getElementsByTagName('canvas')[0].addEventListener( ... )

An advice - when you don't know what's going on, figure it yourself by printing out stuff to console - console.log(canvas) would have told you.

Upvotes: 0

Related Questions