34

I have the following div :

<div id="new" style="position: absolute; z-index: 100; top: 210px; width: 195px..

What is the best way to increase the top property when an event occurs?

Note that I've tried: $('#new').css('top')+10 but the problem is that .css returns string.

5 Answers 5

129

The simplest way is to use the += operator:

$( '#new' ).css( 'top', '+=10px' );
Sign up to request clarification or add additional context in comments.

2 Comments

Aside note for new comers. This only works for JQuery greater than 1.6
Any ideas on how to make this responsive? On screen resize, instead of adding 10px to the amount in the media query, it sticks to the original amount from the larger screen size.
38

You can use the parseFloat function to get only the initial numeric part and convert it from a string to a number. For example:

var n = $('#new');
n.css('top', (parseFloat(n.css('top')) + 10) + 'px');

As a side note, if you want to change multiple elements' positions all at once, that could be:

$('.someClass').css('top', function(i, v) {
    return (parseFloat(v) + 10) + 'px';
});

But if you are just trying to animate an element over time, take a look at jQuery's .animate method.

Comments

2
var el = $('#new');
el.css('top', (parseInt(el.css('top'), 10) + 10) + 'px');

1 Comment

Yes, that's what the +10 bit is for.
2

I would say create a variable, increment the variable, and then reset the property using the new value, like this

var topProperty = 0;   //You can also populate this variable with the current value.

then in your click event

{
topProperty += 10;
$('#new').css('top', topProperty + 'px');
}

Comments

1
var New = $("#new");

function onEvent()
{
   New.css("top", parseFloat(New.css("top")) + 10 + "px");
}

by adding the seconds parameter of to css your setting the property.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.