Using same onmouseover function for multiple objects

Posted by phpscriptcoder on Stack Overflow See other posts from Stack Overflow or by phpscriptcoder
Published on 2010-05-15T15:46:00Z Indexed on 2010/05/15 16:14 UTC
Read the original article Hit count: 274

I'm creating a building game in JavaScript and PHP that involves a grid. Each square in the grid is a div, with an own onmouseover and onmousedown function:

for(x=0; x < width; x++)
{
    for(y=0; y < height; y++)
    {
        var div = document.createElement("div");
        //...
        div.onmouseclick = function() {blockClick(x, y)}
        div.onmouseover = function() {blockMouseover(x, y)}
        game.appendChild(div);
    }
}

But, all of the squares seem to have the x and y of the last square that was added. I can sort of see why this is happening - it is making a pointer to x and y instead of cloning the variables - but how could I fix it? I even tried

for(x=0; x < width; x++)
{
    for(y=0; y < height; y++)
    {
        var div = document.createElement("div");
        var myX = x;
        var myY = y;
        div.onmouseclick = function() {blockClick(myX, myY)}
        div.onmouseover = function() {blockMouseover(myX, myY)}
        game.appendChild(div);
    }
}

with the same result.

I was using div.setAttribute("onmouseover", ...) which worked in Firefox, but not IE. Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about onmouseover