Detect Event Properties

Let’s say I’m trying to create a box that will follow the mouse around on the screen. Here’s the HTML / CSS:


<style type="text/css">
#follow {
    height:100px;
    width:100px;
    position:absolute;
    background-color:#0f0;
}
</style>
<div id="follow"></div>

Let’s also assume that I have a nice cross-browser Event Listener function that ensures there’s an event variable passed along, but I’m making my own “figure out the mouse position” function. This latter function will look something like this:


function mousePos(event) {
    if (event.pageX) {
        
        // W3C model
        
    } else {
        
        // IE model
        
    }
}
addEvent(document, "mousemove", mousePos);

The problem with this is that, every single time the mouse moves, it goes through that if-then statement. Really, it only needs to it once, when it first creates the function:


var mousePos;
if (...) {
    mousePos = function (event) {
        ...
    }
} else {
    mousePos = function (event) {
        ...
    }
}

But I’m not sure what to check for in this new if-then statement. In the first one, I looked for “event.pageX”. But that only works if there’s an event to… well… check for. I’d rather not just use browser detection; all the cool JavaScript coders detect features rather than browsers. So this is the best I can come up with:


var mousePos;
addEvent(document, "mousemove", createFunction);
function createFunction(event) {
    if (event.pageX) {
        mousePos = function (event) {
            ...
        }
    } else {
        mousePos = function (event) {
            ...
        }
    }
    removeEvent(document, "mousemove", createFunction);
}

But this isn’t really ideal, because it creates closure (right? I’m still learning about those), which I’ve heard negatively affects performance. I don’t need to use a closure, so I’d rather not.

Are there any other options available to me?

You’re wanting a lazy definition.

We can simulate it without making things too tricky for you with this:


var mousePos = function () {
    if (event.pageX) {
        return function (event) {
            // W3C model
        }
    } else {
        return function (event) {
            // IE model
        }
    }
};

When this code is run, it reassigns mousePos to whichever function you need.
Each call to mousePos will be only to that one function from thence forward.