0

I have a project using Raphael to draw and animate paths. The project is intended to have multiple divs with similar paths, with animations that trigger on mouseover. At the moment, the divs are populating properly, but the animations are only happening in the last div created. How do I make the script distinguish between the divs to animate them individually?

Example HTML:

<div id="box" class="con1"></div>
<div id="box" class="con2"></div>

Example CSS:

#box {
    width: 100px;
    height: 50px;
    float: left;
}
.con1 {
    background-color:#6634FD;
}
.con2 {
    background-color:#2BA18D;
}

Example JS:

var divs = document.getElementsByTagName("div");

function init() {
    for(var i = 0; i < divs.length; i++){
        var box = divs[i];
        var boxheight = box.offsetHeight;
        var boxWidth = box.offsetWidth;
        var paper = Raphael(box,boxWidth,boxheight);
        var path1 = paper.path("M20,10 l25,0").attr({'stroke-width': 2,stroke:"#FF0000"});
        var path2 = paper.path("M21,10 l-25,0").attr({'stroke-width': 2,stroke:"#FF0000"});

        box.addEventListener("mouseover", function() {
            paper.setStart();
            path1.animate({path:"M20,10 l5,5 l5,-5 l5,5"}, 200); 
            path2.animate({path:"M21,10 l-5,5 l-5,-5 l-5,5"}, 200); 
            cat = paper.setFinish();
        });
        box.addEventListener("mouseout", function() {
            paper.setStart();
            path1.animate({path:"M20,10 l25,0"}, 200);
            path2.animate({path:"M21,10 l-25,0"}, 200); 
            cat = paper.setFinish();
        });
     }
}

init();

http://fiddle.jshell.net/BlueInkAlchemist/dneyhvm1/10/

1 Answers1

0

I wonder how many headaches Javascript closures have caused... probably quite a few :) Your code is fine, you just need to move the inside of the for loop into a separate function to create a new scope since in Javascript, closures are created on a function level, not block level.

for(var i = 0; i<divs.length; i++){
  createDiv(i);
}

function createDiv(i){
  var box = divs[i];
  ...
}

Check out this forked fiddle to see a working example.

If you want to read more on closures, I reccomend e.g. this question or possibly this one.

Community
  • 1
  • 1
Tadeáš Peták
  • 567
  • 2
  • 13