LoginSignup
4
4

More than 5 years have passed since last update.

押すと上にスルスルっと戻るJavaScriptモジュール

Posted at

動作そのものっていうより、JavaScriptでのnamespaceの実装とか、prototypeを使ったモジュールを作ったりとかの練習をしたかった感じです。

var ns = (function(exports) {
  var Raise = function constructor() {
    this._init_handler = function(func) {
      window.addEventListener('load', func);
    };
  };

  Raise.prototype.register = function(id) {
    var to_top = function(e) {
      var scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
      if (scroll_top > 0) {
        var diff = Math.max(scroll_top / 2, 20);
        window.scrollTo(0, scroll_top - diff);
        window.setTimeout(to_top, 25, e);
      }
    };

    this._init_handler(function() {
      var target = document.getElementById(id);
      target.addEventListener('click', to_top);
    });
  };

  exports.Raise = Raise;
  return exports;
})({});


var RAISE_BUTTONS_ID = 'raise-top';
var raiser = new ns.Raise();
raiser.register(RAISE_BUTTONS_ID);

あとは<div id="raise-top"></div>みたいなもんを置いてあげて、cssで見た目を整えてあげればスルッとのぼるアレになります。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4