rohan_vg
rohan_vg

Reputation: 1129

Raphael.js onmouseover onmouseout event

I've made 4 rectangles in raphael.js using the for loop. When I apply events such as onmouseover or onmouseout it applies only to the last rectangle created. I know something is wrong in my code. Please provide a solution and is there a way to simplify the code?

JS Fiddle Link

window.onload = function(){
    var paper = Raphael(0,0,640,540);

    for (i=0;i<2;i++){
        for (j=0;j<2;j++){
            var boxes = paper.rect(0+(j*320),0+(i*270),320,270).attr({fill:'#303030',stroke:'white'});
            boxes.node.onmouseover = function () {
                boxes.attr("fill", "blue");
            };
            boxes.node.onmouseout = function () {
                boxes.attr("fill", "#303030");
            };
        }
    }    
}​

Upvotes: 0

Views: 1348

Answers (1)

Qnan
Qnan

Reputation: 3744

This is an extremely common mistake in javascript. You reuse the boxes variable, so when any of the handlers are executed, it points to the last value it had.

The common way of overcoming this is to wrap the code inside the loop in a function call:

window.onload = function() {
var paper = Raphael(0, 0, 640, 540);

for (i = 0; i < 2; i++) {
    for (j = 0; j < 2; j++) {
        (function(i, j) {
            var boxes = paper.rect(0 + (j * 320), 0 + (i * 270), 320, 270).attr({
                fill: '#303030',
                stroke: 'white'
            });
            boxes.node.onmouseover = function() {
                boxes.attr("fill", "blue");
            };
            boxes.node.onmouseout = function() {
                boxes.attr("fill", "#303030");
            };
        })(i, j);
    }
}
}

Upvotes: 3

Related Questions