Skip to content

Instantly share code, notes, and snippets.

@nicordev
Created May 17, 2019 13:16
Show Gist options
  • Save nicordev/75b6172b2e261eb7d17bf90e7da8eede to your computer and use it in GitHub Desktop.
Save nicordev/75b6172b2e261eb7d17bf90e7da8eede to your computer and use it in GitHub Desktop.
Basic javascript object to animate DOM elements
/**
* Object containing methods to animate DOM elements
*
* @type {{rotate: animator.rotate, moveY: animator.moveY, moveX: animator.moveX}}
*/
var animator = {
/**
* Rotate a DOM element using CSS property transform and the deg unit
*
* @param element
* @param maxAngle
* @param step
*/
rotate: function (element, maxAngle = 360, step = 1, startingAngle = 0) {
var angle = startingAngle;
nextFrame();
function nextFrame() {
element.style.transform = "rotate(" + angle + "deg)";
angle += step;
// Safety in case of infinite rotation
if (angle >= Number.MAX_SAFE_INTEGER) {
angle = 30;
} else if (angle <= Number.MIN_SAFE_INTEGER) {
angle = -30;
}
if (
maxAngle >= 0 && angle <= maxAngle ||
maxAngle < 0 && angle >= maxAngle
) {
requestAnimationFrame(nextFrame);
}
}
},
/**
* Move a DOM element horizontally by setting a relative position
*
* @param element
* @param distance
* @param step
*/
moveX: function (element, distance = 0, step = 1) {
var x = 0;
element.style.position = "relative";
correctStep();
nextFrame();
/**
* Make changes for the next animation frame
*/
function nextFrame() {
x += step;
element.style.left = x + "px";
if (distance >= 0) {
if (x > distance) {
element.style.left = distance + "px";
}
if (
x < distance
) {
requestAnimationFrame(nextFrame);
}
} else {
if (x < distance) {
element.style.left = distance + "px";
}
if (x > distance) {
requestAnimationFrame(nextFrame);
}
}
}
/**
* Correct the step sign to avoid infinite move
*/
function correctStep() {
if (distance >= 0) {
step = Math.abs(step);
} else {
step = -(Math.abs(step));
}
}
},
/**
* Move a DOM element vertically by setting a relative position
*
* @param element
* @param distance
* @param step
*/
moveY: function (element, distance = 0, step = 1) {
var y = 0;
element.style.position = "relative";
correctStep();
nextFrame();
/**
* Make changes for the next animation frame
*/
function nextFrame() {
y += step;
element.style.top = y + "px";
if (distance >= 0) {
if (y > distance) {
element.style.top = distance + "px";
}
if (
y < distance
) {
requestAnimationFrame(nextFrame);
}
} else {
if (y < distance) {
element.style.top = distance + "px";
}
if (y > distance) {
requestAnimationFrame(nextFrame);
}
}
}
/**
* Correct the step sign to avoid infinite move
*/
function correctStep() {
if (distance >= 0) {
step = Math.abs(step);
} else {
step = -(Math.abs(step));
}
}
}
};
@nicordev
Copy link
Author

Demo on JS Fiddle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment