allouis
allouis

Reputation: 99

changing css property relative to eq().. jQuery/JavaScript

i am trying to change the 'left' property of a group of divs dependant on their eq() value. i will show a basic code of what i'm trying to do! any help will be appreciated

HTML:

<html>
<body>
<div class"item-holder"></div>
  <div class"item item-one"></div>
  <div class"item item-one"></div>
  <div class"item item-one"></div>
  <div class"item item-one"></div>
</div>
</body>
</html>

CSS:

.item-holder {
position:relative;
width:100px;
}
.item {
position:absolute;
width:25px;
float:left;
}

jQuery:

$(document).ready(){
var itemWidth = $('.item-holder').width()/$('.item').size();
  $('.item').css({
    'left':$('.this').eq()*itemWidth+'px'
  });
};

please not this is not the full code i can post it if it makes more sense, the reason i need the left value to be created in jQuery is because i'd like to reuse this code in several different places and will use a different number of 'items' each time! any help is welcomed and taken onboard

Upvotes: 3

Views: 538

Answers (2)

Ram
Ram

Reputation: 144699

You can use css function.

.css( propertyName, function(index, value) )

$('.item').css('left', function(ind, v){
    return (ind * itemWidth) + 'px'
})

Note that by using $('.this'), you are selecting elements with class of this, for creating a jQuery object from this object you should code $(this).

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382264

What you seem to need is the index :

$('.item').each(function(){
    $(this).css({
       'left':$(this).index()*itemWidth+'px'
    });
});

Note that you have a few errors in your code :

  • you probably didn't want to close your first div and letting it empty
  • when setting a class, don't forget the = operator

Demonstration

Upvotes: 2

Related Questions