javascriptsvgraphael

Raphaeljs hover on each element of the associative array


I am using Raphael.js to draw a map and mark cities on it.

You can see the code here.

I have a set of elements - the circles around the map, (each circle stands for a city) that I want to perform specific actions when I am hovering on.

The problem is, that I can't write a single function for all of them. I have to write the same function for each element.

How do I solve this problem?

I tried:

for (var city in cities) {
    cities[city].hover(
        function () {
            cities[city].attr({"fill": "#FF5B3A"});
        },
        function () {
            cities[city].attr({"fill": "none"});
        }
    );
}

but after that, when I am hovering over any city - it paints the last city in Red, not the city I am hovering over.

Please suggest a solution.


Solution

  • You would need to create a closure and/or use 'this', so the created function would know to which element it applied, and not just the last element in the for loop.

    There's a couple of ways to do that, one of which would be an immediate function to create function scope of which city its referring to.

    Or you can just use 'this' to refer to the correct element.

    for (var city in cities) {
           cities[city].hover(function () {
             this.attr({"fill": "#FF5B3A"});
           },
           function () {
             this.attr({"fill": "none"});
           })
    };
    

    jsfiddle