Home » Jquery » javascript – How can I animate an element from a static layout position to an absolute layout position?

javascript – How can I animate an element from a static layout position to an absolute layout position?

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a form and inside this form a button. Initially the button is statically positioned at its default position based on usual layout. On an event (in the example below, button click) I want to move it to the center of the form through animation and during this animation doing a horizontal flip (using scale transform) and when the animation is in the middle (when the rendered width is 0) changing the contents of the button to a paragraph that once loaded will show an animation probably done with svg and a link.

This snippet does a part of what I want (everything until the second part of the flip with changing the contents and resizing the button to be bigger), but without an initial static position from which to start the animation:

var form = $("form")
var button = $("button")

button.on("click", function(){
  var x = (form.outerWidth() - button.outerWidth()) / 2;
  var y = (form.outerHeight() - button.outerHeight()) / 2;

  button.css({
  	transform: `translateX(${x}px) translateY(${y}px) scaleX(0)`
  });
})
form {
  background: #aaa;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
  position: relative;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  position: absolute;
  left: 0;
  top: 0;
  
  transition: transform 1s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <p>Hello World</p>
  <button onclick="return false;">Do something</button>
</form>

(https://jsfiddle.net/silviubogan/L1ogpf6a/)

How can I achieve what I want in the most correct manner? Please note that the rest of the form should remain in place.

Thank you.

How to&Answer:

There’s two ways you can do this. First is using setTimeout (reference) with 1000ms as a parameter, since your css animation lasts 1 second, and a callback function that displays the SVG. The second is using jQuery animate (reference) instead of css, and using the parameter complete to show your SVG. Since you are already using css for the animation, let’s go with the first option:

button.on("click", function(){
  // hide button
  window.setTimeout(transform2, 1000);
})

function transform2() {
  // change contents
  // resize button
}

Example fiddle: https://jsfiddle.net/eynL91qu/