March 30, 2012

giving top positions to li using variables in jquery

Question by user1302513

hello friends i want to set position to every <li> using jquery i have tried following code but its not working as i want

<script>
$(document).ready(function(){

var t = 10;
var j = 0;

function cycle(){

var l = $('ul#move li').length - 1;
alert(l);
 $('ul#move li:eq('+j+')').css('top',t + 'px');

 if(j == l)

 {
     j=0;
     t = 10;
 } 
 else
 {
 j++;
 t = t+10;
 }

cycle();
}
})
</script>

html

<ul id="move">
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
</ul>

CSS

<style>
ul#move
{
    position:relative;
    width:300px;
    border:solid;
    font-size:3em;
    height:300px;
}
ul#move li
{
    list-style:none;
    margin:0;
    padding:10px;
    position:absolute;
}
</style>

i want to set top positions to every <li> the gap shuld be 10 px in every <li>

Please help

thanks in advance

Answer by Starx

I have a very strong feeling you are trying to do this

var lis = $('ul#move li')
var l = lis.length - 1;
var j, t;
lis.each(function(index) {
   if(j ==1) {
      j = 0;
      t = 0;
   } else { 
      j++;
      t += 10;
   }
   $(this).css('top',t + 'px');
});

Demo

However, If gap is the only problem. A simple CSS can do the trick

#move li { margin-top: 10px; }

Demo


Update

Animate li can be done like this

var lis = $('ul#move li')
var step = 30;
lis.each(function(index) {
    $(this).animate({
        'top': (index*step)+ 'px'
    });
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!