I have multiple divs which showcase some of the projects I have worked on(lets call each div's class project) . When project is hovered over(Jquery's MouseOver), a div that is contained within it (lets call each class of this type githublink) which has a link to the GitHub account and the website link for that respective project fades in, and vice versa for mouseleave and fadeout. The design acts exactly as how I expect it to react, however when I hover over any of the five project div's the last project div's githublink is always the one fading in and fading out. I concluded that the reason for this is because of the for loop I am using to assign the mouseOver and MouseLeave Events. I am only going to include this specific javascript code and not the HTML code because I have debugged the javascript code and looked at the Chrome Dev Tools and found that after each iteration of the for loop the right element is being retrieved and assigned, however once the for loop is done all the eventhandlers affect the last GitHubDiv.
Below Is My JS Code
var numprojects=document.getElementsByClassName("project");
console.log(numprojects.length);
if(numprojects){
for(i=0; i<=numprojects.length-1; i++){
console.log(i);
currentclass=".project:eq("+i+")";
currentgithublink=".githublink:eq("+i+")";
if($(currentclass)){
$(currentclass).mouseover(function(){
$(currentgithublink).fadeIn("fast","linear");
})
$(currentclass).mouseleave(function(){
$(currentgithublink).fadeOut("fast","linear");
})
}
}
}
How to rewrite the same code using a for loop to save space but at the same time to avoid this issue. I think it has something to do with the anonymous functions, but most importantly WHY and how to fix it.
**UPDATE After reading about closure, I updated my code to do the following now an event isnt triggered at all for any of the projects. **
if(numprojects){
console.log("entered projects");
for(i=0; i<=numprojects.length-1; i++){
console.log("entered loop");
mouse[i]=".project:eq("+i+")";
currentgithublink[i]=".githublink:eq("+i+")";
$(mouse[i]).mouseover=(function(index){
return function(){
$(currentgithublink[i]).fadeIn("fast","linear");
}
})
$(mouse[i]).mouseleave=(function(index){
return function(){
$(currentgithublink[i]).fadeOut("fast","linear");
}
})
}
}
2ND UPDATE Tried a different method... Still cant figure out why this wont work
var currentclass=[];
mouseover=[];
mouseleave=[];
if(numprojects){
for(i=0; i<=numprojects.length-1; i++){
currentclass[i]=".project:eq("+i+")";
mouseover[i]=getFadeIn(i);
mouseleave[i]=getFadeOut(i);
$(currentclass[i]).mouseover=mouseover[i];
$(currentclass[i]).mouseleave=mouseleave[i];
}
}
function getFadeIn(i){
currentgithublink=".githublink:eq("+i+")";
return function(){
$(currentgithublink).fadeIn("fast","linear");
}
}
function getFadeOut(i){
currentgithublink=".githublink:eq("+i+")";
return function(){
$(currentgithublink).fadeOut("fast","linear");
}
}