OGP1234 OGP1234 - 2 months ago 12
Javascript Question

FireFox Javascript event handling

I have the following function that works in Chrome/IE

for(var i = 0; i < 5; ++i) {
document.all["elems" + i].onscroll = getFunc("onScrollAdj(document.all['tb" + i + "']);");
}

function getFunc(jsString) {
return new Function(jsString);
}


However I get
ReferenceError: event is undefined
.

I have tried to re-write the function to include an event however I then get another error
var i is undefined
.

document.all["elems" + i].onscroll = onScrollAdj(event, document.all['tb" + i + "');


Is there any way to ensure both event and attributes can be passed?

Answer

however I get 'ReferenceError: event' is undefined.

That's because you're trying to use event without declaring it as an argument. That only works on Microsoft browsers, which make event a global, and Chrome which throws a bone to Microsoft-only code. You will need to declare the argument.

There's no need for new Function virtually ever, and certainly not in this case:

for(var i = 0; i < 5; ++i) {
    document.all["elems" + i].onscroll = getFunc(i);
    // ------------------------------------------^
}

function getFunc(i) {
// --------------^
    return function(event) { onScrollAdj(event, document.all['tb' + i]); };
    // -------------^--------------------^
}

Note that you'll have to ensure that onScrollAdj accepts event:

function onScrollAdj(event, tbThingy) {
// ------------------^
Comments