Aiden Bell
Aiden Bell

Reputation: 28386

CSS Translate already translated element

I'm trying to apply the "bounce" effect from animate.css to an element that already has the following property in it's style element (added by a third-party JS library):

style="... transform: translate(625px, 471px); ..."

When applying the following bounce animation:

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    -webkit-transform: translateY(0);
    -ms-transform: translateY(0);
    transform: translateY(0);
  }

  40% {
    -webkit-transform: translateY(-30px);
    -ms-transform: translateY(-30px);
    transform: translateY(-30px);
  }

  60% {
    -webkit-transform: translateY(-15px);
    -ms-transform: translateY(-15px);
    transform: translateY(-15px);
  }
}

The element's position prior to the animation doesn't stick and the element moves to the top of the page and animates there.

Is there a variation on this CSS that will apply a bounce effect without overriding the transform already on the element via the style attribute? I don't really want to hack in to a third party library to wrap the element or anything unless I can help it.

Thanks in advance.

Upvotes: 2

Views: 926

Answers (1)

jwahdatehagh
jwahdatehagh

Reputation: 115

You have to wrap it in another element, if you want relative animations. You don't have to hack into a third party library to do so. You can dynamically insert a div without messing with existing code.

I'd do the following:

// `element` is the element you want to wrap
var parent = element.parentNode;
var wrapper = document.createElement('div');

// set the wrapper as child (instead of the element)
parent.replaceChild(wrapper, element);
// set element as child of wrapper
wrapper.appendChild(element);

Read more here: https://developer.mozilla.org/en-US/docs/Web/API/Node.replaceChild

Upvotes: 2

Related Questions