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?

Answers


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);
} 

Need Your Help

how to shorten content text of html string while binding to view with ngBindHtml

javascript angularjs angularjs-filter

I'm binding an html string to view using ngBindHtml. the string contents are plain text along with anchor elements.