Reputation: 10388
Hi i want to apply css left
property in %
for multiple div how will i do . i have tried below code
HTML
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text1 <br>
</a>
</div>
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text2 <br>
</a>
</div>
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text3 <br>
</a>
</div>
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text4 <br>
</a>
</div>
In JS
$(".inner-nav").each(function(){
$(this).find("a:first").css("left", function( index ) {
var f= index*25;
f=f+"%";
return f;
});
});
Upvotes: 1
Views: 93
Reputation: 74738
I think your issue is index of anchor which is always 0
so 0%
is applied to each anchor so you can try this:
$(".inner-nav").each(function () {
var idx = $(this).index(); // get the div's index
$(this).find("a:first").css("left", function (index) {
var f = idx * 25; // and use it here.
f = f + "%";
return f;
});
});
To simplify this you can use it:
$(".inner-nav").each(function (idx) {
$(this).find("a:first").css("left", idx * 25 + "%");
});
Upvotes: 2
Reputation: 36794
The issue with your code is that you are defining index
in the wrong place. You are getting the index
of the element that css()
is being called on, but it will always be the first in the set, so index
will always be 0:
$(".inner-nav").each(function (index) {
$(this).find("a:first").css("left", function () {
var f = index * 25;
f = f + "%";
return f;
});
});
The each()
loop isn't needed. Many jQuery methods, including css()
handle looping through each element matched to the selector on it's own:
$(".inner-nav").find("a:first").css("left", function( index ) {
var f= index*25;
f=f+"%";
return f;
});
Upvotes: 1
Reputation: 20418
Try this
$(".inner-nav").each(function (i) {
var inn = $(this).index();
var f = parseInt(inn) * 25;
var cf = f + "%";
$(this).find("a:first").css("left", cf);
});
Upvotes: 0
Reputation: 82251
You have not passed index as function attribute. Due to which its not define inside loop.also index is 0 based here. so first anchor of first div will have 0% left. Try this:
$(".inner-nav").each(function(index){
$(this).find("a:first").css("left",index*25+'%');
});
Upvotes: 0