Question

i'm trying to link an event to a raphael.js object through hover event, but it doesnt work. Here is my code :

var paper = Raphael('menu', 400, 400);

for(var i = 0; i < 6; i++) {

    var x = 200,
        y = 200;

    var rx = Math.sin(i / 6 * 2 * Math.PI),
        ry = Math.cos(i / 6 * 2 * Math.PI);

    var hx = x + rx * 100,
        hy = y + ry * 100;

    var hexa  = polygon(hx, hy, 6, 50);

    hexa.attr("fill", "rgb(212, 212, 212)");
    hexa.attr("stroke-width", 0);

    var hoverTitle = paper.text(hx + rx * 70, hy + ry * 70, "foo " + i);

    var hoverIn = function() {

        this.animate({fill: "rgb(247,245,240)"}, 300, '<>');
        hoverTitle.show();
        hoverTitle.animate({opacity:1}, 200, '<>');
    }

    var hoverOut = function() {

        this.animate({fill: "rgb(212, 212, 212)"}, 300, '<>');
        hoverTitle.animate({opacity:0}, 200, '<>');
        hoverTitle.hide();
    }

    hexa.hover(hoverIn, hoverOut, hexa, hexa);
}

function polygon(x, y, N, side) {

    var path = "", n, temp_x, temp_y, angle;

    for(n = 0; n <= N; n++) {

        angle = n / N * 2 * Math.PI;

        temp_x = x + Math.cos(angle) * side;
        temp_y = y + Math.sin(angle) * side;

        path += (n === 0 ? "M" : "L") + temp_x + "," + temp_y;
    }

    return paper.path(path);
}

i want each hexagon to display it's foo when hovered, but i dont understand why it's always refering to the last foo... Should i declare each one separately ?

Here is a fiddle

Was it helpful?

Solution

This happening because you define hoverTitle as global variable, so when you try to manipulate with it in callbacks you always use last one.

The solution is to define hoverTitle as local property for each hexagon, for example like this:

hexa.hoverTitle = paper.text(hx + rx * 70, hy + ry * 70, "foo " + i);

And then manipulate with this property in callbacks:

this.hoverTitle.show();
this.hoverTitle.animate({opacity:1}, 200, '<>');

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top