0

I know there is already a function in jquery that allows you to animate. But, I want to know how make an element ease into a position I want it to go with javascript. I have a simple function where if you click on a button a div will appear and it will slide down a little bit. The problem is that the animation of the sliding down is a bit choppy sometimes, but other times its fine. Is there a way to make the animation smooth everytime I click the button?

Snippet

document.querySelector('div#ex2 button').onclick = function() {
  var counter;

  // shows the div
  document.querySelector('div#reveal').style.display = "block";

  // used to decrease bottom position
  var dec = 20;
  counter = setInterval(moveD, 10);

  // moves the div down
  function moveD() {
      dec -= 2;
      document.getElementById('reveal').style.bottom = dec + "px";
      if (dec < 1) {
        clearInterval(counter);
        log('function is done');
        document.getElementById('reveal').style.bottom = 0;
      } // moveD if
    } // function moveD


}; // onclick function
div#reveal {
  height: 100px;
  width: 300px;
  background: purple;
  padding: 5px;
  position: relative;
  bottom: 20px;
  display: none;
  color: white;
  text-align: center;
  vertical-align: center;
  margin: 10px 0;
}
<div id="ex2">
  <h2>Example 2</h2>
  <p></p>
  <h4>results:</h4>
  <button>Click it</button>
  <div id="reveal">This will be revealed</div>
</div>
Pierre C.
  • 1,426
  • 1
  • 11
  • 20
black_yurizan
  • 407
  • 2
  • 7
  • 19
  • JS animation will generally be a little jumpy, to make it smoother you should really look into libraries which have been built specifically for that purpose. Also, CSS animations are the way to go for the smoothest animation provided they're supported by everyone you need to cater for. – DBS Apr 08 '16 at 15:01

2 Answers2

0

I think you can solve your issue just by using CSS animation honestly. Keep in mind, you should always use CSS to do something instead of javascript if at any way possible.

w3schools link

Specifically (you can scrolldown a bit) there is an animation-timing-function which you would be interested in.

Dellirium
  • 1,362
  • 16
  • 30
0

Check out all these easing functions: https://github.com/danro/jquery-easing/blob/master/jquery.easing.js.

If you want to see them in use check out my animation library at http://nanimation.js.org/.

Check this for more information on the functions and their parameters: jQuery easing function — variables' comprehension.

Community
  • 1
  • 1
IMTheNachoMan
  • 5,343
  • 5
  • 40
  • 89