Search code examples
windowscrolltop

Moving element on Window scroll


You'll see in this JsFiddle https://jsfiddle.net/xpvt214o/402281/ there is an image scrolling within another one on window scroll. How can I modify the below so that it doesn't start scrolling until it hits that element (after all the br tags)? I've tried offsetting it but not getting anywhere.

It would also be fine if it just scrolled a lot slower.

jQuery(document).ready(
function() {

var $w = $(window);
var $d = $('.oh');

$(window).scroll(function(event) {
  var st = $w.scrollTop();

  _x = st;

  lastScrollTop = st;

  $d.css('bottom', _x);      

});

});

Here's an example of what I'm trying to achieve https://www.sketchapp.com/


Solution

  • I found this which does what I'm looking for

    https://codepen.io/JTParrett/pen/BkDie

    $.fn.moveIt = function(){
    var $window = $(window);
    var instances = [];
    
    $(this).each(function(){
    instances.push(new moveItItem($(this)));
    });
    
    window.addEventListener('scroll', function(){
    var scrollTop = $window.scrollTop();
    instances.forEach(function(inst){
      inst.update(scrollTop);
    });
    }, {passive: true});
    }
    
    var moveItItem = function(el){
    this.el = $(el);
    this.speed = parseInt(this.el.attr('data-scroll-speed'));
    };
    
    moveItItem.prototype.update = function(scrollTop){
      this.el.css('transform', 'translateY(' + -(scrollTop / this.speed) + 
    'px)');
    };
    
    // Initialization
    $(function(){
      $('[data-scroll-speed]').moveIt();
    });