Skip to content Skip to sidebar Skip to footer

Dynamic Transform Style Property While Scrolling

I'm in a blind spot with my small jQuery script. The point is that I'm trying to make an element to rotate, and to apply the rotation value dynamically as the user is scrolling thr

Solution 1:

Check this example I've made without jQuery, which shows how to rotate an element based on the scroll position of the window, but only once the element is in view.

I've decided to do this without jQuery because it's better for performance, working directly with the DOM instead of passing through jQuery, and also because it's relatively simple code, understandable.

  1. Find out how much was scrolled
  2. Get the target's element absolute position
  3. Calculate if the element is within the viewport (if not, break)
  4. If it's in, save the scroll value at that point
  5. Subtract that value from the current scroll value to get the value from that point on
  6. Use the new value as baseline for the transformation

var elm = document.querySelector('b');

var onScroll = (function(){
  var startPos;
  
  functionrun(){
    var fromTop = window.pageYOffset, 
        rect = elm.getBoundingClientRect(),
        scrollDelta;

    // check if element is in viewportif( (rect.top - window.innerHeight) <= 0 && rect.bottom > 0 )
       startPos = startPos === undefined ? fromTop : startPos;
    else{
      startPos = 0;
      return;
    }
    
    scrollDelta = (fromTop - startPos) * 1; // "speed" per scrolled frame
    elm.style.transform = `translateX(${scrollDelta}px) rotate(${scrollDelta}deg)`;
    
    console.clear();
    console.log(scrollDelta);
  }
  
  run();
  
  return run;
})()

window.addEventListener('scroll', onScroll);
html, body{ height:100%; }
body{ height:1500px; }

b{ 
  position:fixed;
  top: 20px;
  left:20px;

  width:100px;
  height:100px;

  background:red;
}
<b></b>

inspect the <b> element while scrolling and see that it only gets transform when it is in view.

Post a Comment for "Dynamic Transform Style Property While Scrolling"