• This is a read only backup of the old Emudevs forum. If you want to have anything removed, please message me on Discord: KittyKaev

Jquery loop

Vitrex

Moderator
hello, emudevs, heh does anybody can help me solve second problem. i have 2 div elements features_box
they both have different id
features_box_1
features_box_2
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
Code:
for (var iter = 0; iter<=2; iter++){
			
				var container =$('#features_box_'+iter);
				var content =$('#features_content_'+iter);
					
				
					
					$(container).click(function( event) {
						$(content).slideDown();
						
						$(container).mouseleave(function( event ) {
							$(content).slideUp();
						});
					});
					
				
			
			}

maybe i use wrong loop?
 

Rochet2

Moderator / Eluna Dev
This might help you out:
http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript
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:
https://jsfiddle.net/nxsho655/1/
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.
 
Top