ZoEM
ZoEM

Reputation: 852

Alerting .position() method not working as it should be

I've got an animation of the earth rotating around the sun. The sun stays put, but the earth keeps changing position.

I want to alert a message saying "Aligned!" or something when the earth is perfectly vertically aligned with the sun. I've been testing it out but I can't get the alert message any time other than when the page has loaded and the conditial statement corresponds to the position of the earth when the page has loaded, before the earth even gets close to aligning.

The below code will only show the position of the earth as its position is above 400. So if I say like, alert message when positionplanet.left == positionsun.left, I will get nothing.

var possun = $( "#Sun" );
var positionsun = possun.position();

var posplanet = $( "#Earth" );
var positionplanet = posplanet.position();

if (positionplanet.left >= 400)
{
alert(positionplanet.left + " and " + positionplanet.top);
}

I have a JSfiddle for the animation but for some reason I'm having trouble alerting anything at all other than just random strings. So I'll link it but it'll mainly be for reference. Demo:

Upvotes: 0

Views: 43

Answers (1)

Masala
Masala

Reputation: 96

I haven't checked your maths so I can't prove this definitely, but it seems like the positions never match exactly - which isn't too surprising as we're dealing with irrational numbers of pixels rounded to 10-15 decimals.

If you allow the positions to match to the nearest pixel, though, you can make it work (and no-one should be any the wiser). Also, you need to do the check for every step of the animation, instead of in the global scope like in your JSFiddle (no wonder you only get the alert when you reload the page. :) )

Putting this inside your animate() function did the trick:

var positionsun = $("#Sun").position();
var positionplanet = $("#Earth").position();

if(Math.round(positionplanet.left) == Math.round(positionsun.left))
    alert("aligned!");

Also, make sure you're including jQuery if using jQuery functions (like $(...)).

Upvotes: 2

Related Questions