Jinbom Heo
Jinbom Heo

Reputation: 7400

jquery, Any short version to change top position relatively

I want to add css top position relatively. if its top position is 30px, I want to add its position +30, so its result is 60px.

so I have to do this like this,

$("#btn").css("top", $("#btn").css("top")+30);

is there any shorter way or effecient way to do this.

Upvotes: 1

Views: 5977

Answers (6)

Pablo
Pablo

Reputation: 2854

From jQuery 1.6 you can use:

$("#btn").css("top", "+=30");

Upvotes: 0

Fred
Fred

Reputation: 4221

You should use

$('#btn').css({top: +30});

It just adds 30 to the current value. Simple. This works for any other CSS value as well.

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

If you want you can use the .animate() method which allows increments, and use 0 as duration so that it occurs instantly.

$('#btn').animate({top:'+=10'},0);

example at http://www.jsfiddle.net/gaby/Pre8A/1/

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382736

That would add current top to 30 resulting in 30px30, you should use parseInt:

$("#btn").css("top", (parseInt($("#btn").css("top")) + 30) + 'px');

Upvotes: 0

Haim Evgi
Haim Evgi

Reputation: 125496

another way

$('#btn').css('top', function(index,value) {
  return value +30;
});

Upvotes: 1

dyve
dyve

Reputation: 6023

JavaScript can always be shorter. Use a tool to compress or minify it, don't do it manually.

You can be more efficient by only getting your button once. Also, if you want others to see what you intend, it might be best to use self explaining variable names.

var btn = $("btn");
var top = btn.css("top");
btn.css("top", top + 30);

feel free to shorten this to

var btn = $("btn");
btn.css("top", btn.css("top") + 30);

P.S. The exact position of the element can be different than what you've specified in your CSS. If you experience positioning issues, look into jQuery function offset(), position(), etc -- see http://api.jquery.com/category/css/.

Upvotes: 1

Related Questions