Reputation: 21
I am trying to use a jQuery loop to set a variable that will change in each pass through the loop. the variable would then be applied to a css property. the problem I have is that every css property with the variable has the same value (which is the value at the end of the loop).
pageArray = new Array('web1','web2','web3','web4');
**leftTabHeight** = 0;
for (var p=0;p<pageArray.length;p++){
**leftTabHeight** = parseFloat(p) *100;
$('.left.main').addClass('flip_left');
$('.left.main').css({'width':'482px', 'height':'668px', 'z-index':'11','background':'url("images/snake_tab.png") no-repeat, url("images/book_left_main.png") no-repeat','background-position': '0px '+**leftTabHeight**+'px, 42px 42px','position':'absolute'});
};
HTML:
<div class="web4 left main">
<h3 class="left_button">web 4</h3>
<h4>web 4</h4>
<p>Stuff</p>
</div>
<div class="web4 left bind">
</div>
<div class="web3 left main">
<h3 class="left_button">web 3</h3>
<h4>web 3</h4>
<p>stuff</p>
</div>
<div class="web3 left bind">
</div>
<div class="web2 left main">
<h3 class="left_button">web 2</h3>
<h4>web 2</h4>
<p>Stuff</p>
</div>
<div class="web2 left bind">
</div>
<div class="web1 left main">
<h3 class="left_button">web 1</h3>
<h4>web 1</h4>
<p>Stuff</p>
</div>
<div class="web1 left bind">
</div>
So I want each class to have a background image that is positioned differently. currently they all stack on top at 300px.
Thanks
So, I've placed a console.log(leftTabHeight) within the loop and it does print 0, 100, 200, 300. The 300 is the only one being applied.
Upvotes: 0
Views: 5659
Reputation: 389
The problem is that you are referring to all of the ".left.main“
items. Change those line to $('.'+pageArray[p]+'.left.main').css(...)
and that's it.
Upvotes: 0
Reputation: 21
Okay I've figured this out the problem was I each time the function looped it rewrote all the divs. I needed to add the third class into the jQuery selection as a variable. so this code works:
pageArray = new Array('snake','web_s','web1','web2','web3','web4');
var leftTabHeight = 0;
for (var p in pageArray){
leftTabHeight = parseFloat(p *100);
$('.'+pageArray[p]+'.left.main').addClass('flip_left');
$('.'+pageArray[p]+'.left.main').css({'width':'482px', 'height':'668px', 'z-index':'11','background':'url("images/snake_tab.png") no-repeat, url("images/book_left_main.png") no-repeat','background-position': '0px '+leftTabHeight+'px, 42px 42px','position':'absolute'});
};
Upvotes: 0
Reputation: 2191
You could do something like:
var variable_position = 0;
$('.background_image').each(function(){
$(this).css('background-position', '0px ' + variable_position + 'px 42px 42px');
variable_position += 100;
});
That is assuming your objects that need this have the class "background_image".
Upvotes: 1