Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate DOM properties (scrollTop) using Web Animations

Web Animations is a new w3c spec, just to be clear what we're talking about. Either way, I wanted to scroll to a certain element smoothly. Using jQuery's Animate function this was always a no-brainer, but this seems to not be as simple with Web Animations. Is there any way to use the Web Animation timing functions and apply them to a DOM property (scrollTop). The reason I am asking is that I don't want to load an entire (extra) library just to use its interpolation function whilst doing it with a different technology/library in the rest of my application.

like image 718
David Mulder Avatar asked Sep 30 '22 16:09

David Mulder


2 Answers

You can use Custom Effects to animate scrollTop, e.g.

var a = new Animation(el, function(time) {
    el.scrollTop = el.scrollTop + time * 500;
}, 1000);
like image 63
Yvonne Yip Avatar answered Oct 03 '22 00:10

Yvonne Yip


For the sake of documentation, starting from Yvonne's answer, using core-animation:

<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/core-animation/core-animation.html">

<polymer-element name="animated-scroll">
  <template>

    <style>
      #scroller {
        height: 300px;
        overflow-y: scroll;
      }
    </style>
    <button on-tap="{{animate}}">Scroll it</button>
    <div id="scroller">
      <content></content>
    </div>
    <core-animation id="animation" duration="400" easing="ease-in-out"></core-animation>

  </template>
  <script>
    (function () {

      Polymer({
        animate: function (e) {
          var start = this.$.scroller.scrollTop;
          var end = 500; // px
          var delta = end - start;
          this.$.animation.target = this.$.scroller;
          this.$.animation.customEffect = function (timeFraction, target, animation) {
            target.scrollTop = start + delta * timeFraction;
          };
          this.$.animation.play();
        }
      });

    })();
  </script>
</polymer-element>
like image 23
clyfe Avatar answered Oct 03 '22 02:10

clyfe