Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add css value incrementally

Tags:

jquery

I want to add or subtract the value of 'top' in this css change. Rather then specifying a specific ammount of pixels I would like to add 20px to the current value provided by the external css.

The goal is to make the list move up an down.

$('.up').click(function(){
   $('.list').css('top','-20px');
});

the HTML

<div id="container">
    <ul class="list">
        <li >first item</li>
        <li class="active">second item</li>
        <li>third item</li>
        <li >fourth item</li>
    <ul>
</div>   
<a href="#" class="up">up</a>
<a href="#" class="up">down</a>​
like image 777
patrick Avatar asked May 04 '12 06:05

patrick


2 Answers

Based on your edit:

$('.up').click(function(){
   $('.list').css({position:'absolute', top: parseInt($('.list').css('top'), 10) + 20 + 'px'});
});

Or you can add 20px with each click while using animate like this:

$('.up').click(function(){
   $('.list').css({position:'absolute'});
   $('.list').animate({top: '+=20'});
});

The top property wont work unless you also specify position:

$('.up').click(function(){
   $('.list').css({position:'absolute', top:'-20px'});
});

Change position to absolute or relative as per your needs.

Note that if you want the .list element appear only inside its container while changing top, you need to assign position:relative to parent element and absolute to .list element.

like image 190
Sarfraz Avatar answered Sep 21 '22 21:09

Sarfraz


The .css() method also allows the "+=" and "-=" syntax that .animate() takes. So you can simply do this:

$('.up').click(function(){
   $('.list').css('top','-=20px');
});
like image 40
Doug Avatar answered Sep 22 '22 21:09

Doug