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?
getElementsByTagName()returns anodeList(like an array of DOM objects) so you need to designate which element in thatnodeListyou want to add the listener to.And secondly, your event handler
on_canvas_move()also has the same issue ascanvas.offsetLeftwould be trying to read the.offsetLeftproperty on the nodeList, not on the DOM element. That would give you anundefinedvalue and trying to do math withundefinedgives youNaN.To add just one:
Or, to add all of them: