一定量スクロールで要素移動

by yshrkn

HTML

<button id="btn-toggle">Toggle</button>
<div id="box"></div>
<div id="result"></div>

<div id="spacer"></div>

CSS

#box {
  width: 100px;
  height: 100px;
  background-color: #000;
  transition: all 1s ease-out;
  transform: translateY(0);
  position: relative;
  top: 500px;
}

#box.anim {
  transform: translateY(-500px);
}

#result {
  position: fixed;
  top: 0;
  right: 0;
}

#spacer {
  height: 1000px;
}

JavaScript

(function() {
  var $box = $('#box');
  var windowHeight = 0;
  var elemOffsetTop = 0;


  $('#btn-toggle').on('click', function(event) {
    $box.toggleClass('anim');
  });

  function getScrollTop() {
    windowHeight = $(window).scrollTop() + $(window).height();
    $("#result").text(windowHeight + 'px');
  }

  function getOffsetTop(elem) {
    elemOffsetTop = elem.offset().top;
    console.log(elem+"要素のoffsetトップ:" + elemOffsetTop);
  }

  function init() {
    $(window).on("load scroll resize", function(){
      getScrollTop();
      getOffsetTop($box);

      if(windowHeight > elemOffsetTop) {
        $box.toggleClass('anim');
      }

    });
  }

  init();

}());