View Full Version : Jquery loop

08-22-2015, 12:36 PM
hello, emudevs, heh does anybody can help me solve second problem. i have 2 div elements features_box
they both have different id
so when you click on them i wanna show one more div above them,this works fine if i write code for each box manually, but i wanna make it through loop, since i'm and jquery are enemies long time ago, i can't get loop working, it's shows only the last one box data. doesn't matter on which i click it show only the last one;
here is my code

for (var iter = 0; iter<=2; iter++){

var container =$('#features_box_'+iter);
var content =$('#features_content_'+iter);

$(container).click(function( event) {

$(container).mouseleave(function( event ) {


maybe i use wrong loop?

08-22-2015, 01:26 PM
This might help you out:
See the "closure" point.

Basically you have a function with a variable and the function creates a new function which has access to that variable.
But later the loop changes the meaning of the variable to something else so the inner function also has the meaning changed.
so in short, you are changing container and content in the loop and thus they change for the slide down and up as well.

Here is an example that works:
Basically you need to "capture" the variables to a separate environment so that their meaning does not change.
But seems there is no capture possibility in javascript like in c++ so you need to use functions like that I guess.
In the code above I create a function temporarily in the loop to capture the vars and then execute it immediately.

Also seems on EVERY click you make a new function for the slide up event.
You should probably take that out of the click event.

08-22-2015, 01:52 PM
oh, thanks, seems like more clear right now.