6

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);}
        );
    }
};
2
  • 1
    Just an off topic note, why use brnches & deptmts instead of branches and departments as variables? Good and clear variable names can go such a long way in explaining code. Commented Nov 21, 2012 at 22:50
  • 1
    @MorganWilde: Sorry yes you're right, I should have changed these after copying it all in. I shortened them just for my personal preferences, keeping the same length of chars. On the plus side you still understood what they meant :) ...but yes it's bad practise. Commented Nov 21, 2012 at 23:12

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

6 Comments

+1 as it does answer the requirement ...when I hover over an element in the deptmts array, the corresponding element in the brnches array is then faded in and out. @vletech: As a side-note there is no correlation between the hovered department and the faded branch other than that you rely on them being in the matching/required order. If you find your branches are not always in the same index/order as the departments you will need to match them by something more reliable than the element index.
@Sushanth: Thank you that worked perfectly, I'm still learning so this is one I'll remember.
@FrançoisWahl: You're right I was relying on them being in the same order for both of the arrays, hopefully I won't have to change this.
@vletech .. Glad to have Helped :) .. FrançoisWahl Thanks for pointing at the issue..
@vletech .. You can store the corresponding index or id of brnches in the data attribute of deptmts
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.