Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

There are topics about this, but not realy pointed at my problem.

I'm using iScroll, a jquery plugin. For every scrollbox on my page I need to assign a unique variable. In this case it's gonna be myScroll1, myScroll2 etc.

To make it easily editable, I want the variables to be automatically generated giving the number of div's in wich the scrollbars are in. So, let's say I have 2 divs with these scrollbars. I use the .size() method to count the divs. Then I want a while loop to make the variables. I now have something like this:

var i = 0;
var item_number = $(".portfolio_item").size();

var myScroll = [];
while( i < item_number ) {
    myScroll[i];
    i++;
}

Sooo, I don't want anything generated in the HTML, just the variables. They have to become myScroll1, myScroll2, myScroll3. Depending on the amount of .portfolio_item divs.

I have tried this with php, that's a bit easier for me. But!! I can't use javascript variables in php. So I can't count the amount of .portfolio_item divs :( Thank you! :)

share|improve this question
1  
Do you want to make global variables (if so, reconsider; that's bad practice)? Why a separate one for each item? An array would be much better! –  Jon Jan 20 '12 at 0:24

1 Answer 1

up vote 2 down vote accepted

Bad practice, but you can do this

var i = 0;
var item_number = $(".portfolio_item").size();

while( i < item_number ) {
    window["myScroll" + i] = "foo" + i;
    i++;
}

alert(myScroll0);

better practice is to use a namespace and add to it.

var i = 0;
var item_number = $(".portfolio_item").size();

var foo = {};
while( i < item_number ) {
    foo["myScroll" + i] = "foo" + i;
    i++;
}

alert(foo.myScroll0);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.