art vanderlay
art vanderlay

Reputation: 2463

jquery .animate by % of object X or Y

Due to some css limitations between IE and the rest of the world I am forced to use the .animate as a % rather than px or the objectToMove jumps (IE only) then animates.

So if the following is used

 $('.myClick').click(function() {
  $('.objectToMove').animate({
    top: '+=10%'
          }, 'fast', function() {
    // Animation complete.
  });
});

It will move the objectToMove by 10% of screen height. I would like to move it as 10% of the objectToMove height.

Is this possible without having to get the screen and object height and work out the % of the object to screen height etc?

example

canvas size = 720px

objectToMove = 100px

I want to move objectToMove by 10px not 72px

thx Art

Upvotes: 1

Views: 182

Answers (2)

Alex Ball
Alex Ball

Reputation: 4474

In a simple way,

with

top: '+=' + ( $('.objectToMove').height() / 100 ) * 10;

you can obtain the desired percentage height of the object

Upvotes: 1

Aaron Miler
Aaron Miler

Reputation: 889

Here is what I have. If you are forced to continue to work in percentages this should work.

To start I'm going to get the hieght of the element, and the HTML.

var moveObject = $('.objectToMove').height();
var html = $('html').height();

Then I'm going to find out what moving the object 10% of it's own height would be

var distance = (moveObject/html)*10;

Now, I'm going to move the object 10% of it's height from the top.

$('.objectToMove').animate({
    top: '+='+distance+'%'},1500);

I tested this and it worked for me. Let me know if it doesn't work.

Upvotes: 0

Related Questions