Alon Shmiel
Alon Shmiel

Reputation: 7121

send an event to a function by javascript

I am trying to catch the event of onmousemove and send it to the function mouseMoveOnCanvas.

in the function of mouseMoveOnCanvas I am trying to get: ev.currentTarget.offsetLeft.

I tried to do the next thing:

document.getElementById('canvas_1234').onmousemove = (function (ev) {
    if (ev != null) {
        canvas_id = 'canvas_1234';
        return function () {

            mouseMoveOnCanvas(ev);
            //MouseOverColor(currentTd);
        }
    }
})();

but ev is always null.

I know I can do it with jquery:

$('canvas[id^="canvas_"]').live('mousemove', function (ev) {..}

but I want to do it with javascript.

any help appreciated!

Upvotes: 0

Views: 162

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

You should not use closure that way. Remove it and it should work.

document.getElementById('canvas_1234').onmousemove = function (ev) {
    if (ev != null) {
        canvas_id = 'canvas_1234';
        return function () {

            mouseMoveOnCanvas(ev);
            //MouseOverColor(currentTd);
        }
    }
};

What is happening is that the closure is calling the function by itself(on load) and not by the event. Further, you didn't pass anything on the parameter anyway - like this:

(function(ev) { console.log(ev); })("Hi");

Other point is that there's no reason why to return that anonymous as you're not returning nothing from it. Why not this ?

return mouseMoveOnCanvas(ev);

Upvotes: 1

Related Questions