Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hover array element to fade corresponding element in another array [Closure issue]

What I'm hoping to achieve is when I hover over an element in the deptmts array, the corresponding element in the brnches array is then faded in and out. I've added below what I thought it should be but not really sure where I'm going wrong. Any help would be much appreciated.

var brnches = ["#branch01","#branch02","#branch03","#branch04"]
var deptmts = ["#depart01","#depart02","#depart03","#depart04"]

var brchhov = function() {
    for(var i=0; i<deptmts.length; i++){
        $(deptmts[i]).hover(
            function(){$(brnches[i]).stop(true).fadeTo("fast", 1);},
            function(){$(brnches[i]).stop(true).fadeTo("slow", 0);}
        );
    }
};
like image 225
dev Avatar asked Nov 21 '12 22:11

dev


1 Answers

Classic closure Issue..

var brchhov = function() {
    for(var i=0; i<deptmts.length; i++){
       (function(num){
             $(deptmts[num]).hover(
                 function(){$(brnches[num]).stop(true).fadeTo("fast", 1);},
                 function(){$(brnches[num]).stop(true).fadeTo("slow", 0);}
             );
       })(i);
    }
};

Check Fiddle

like image 58
Sushanth -- Avatar answered Oct 16 '22 14:10

Sushanth --