cui
cui

Reputation: 129

Type error: event is undefined in firefox about javascript

Here is the thing. I'm need to open a new tab and draw something on the new opened tab.

I add event listener like that:

div3.addEventListerner("onmousedown",MouseDown(NewWindow.event),false);

But the firefox throw errors about the code in the MouseDown() function when the page is loading. The error is not throwed when I move the mouse.

function MouseDown(event)
{
if(!event)
    {
    var event = window.event;
    }

X = event.pageX;//Throw error here.
Y = event.pageY;

So, there is anyone who knows how to fix this Problem?????

Upvotes: 3

Views: 2012

Answers (2)

Teemu
Teemu

Reputation: 23406

When you're using addEventListener(), Event object is passed automatically in all browsers supporting the said method. However, you're calling your eventhandler immediately in argument. Instead you should pass a reference:

div3.addEventListener("mousedown", MouseDown, false);

Notice also "mousedown" without on. In the handlerfunction, event always exists, no need to check it for older IEs, since they don't support addEventListener.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Remove the var from var event = window.event. The variable is already declared (as an argument), so re-declaring it with var can only lead to problems.

To be specific, due to hoisting, here is what your code boils down to:

function MouseDown(event) {
    var event; // = undefined
    if( !event) { // always true
        event = window.event; // undefined in modern browsers
    }
    X = event.pageX; // ERROR!
}

Without the var, all is well!

Upvotes: 1

Related Questions