skip to Main Content

I am a complete beginner in JS and front-end. I am working on a website and I have an image in this div with the id main-image.

When the user scrolls down the image I want it to go left slowly and then delete the image.

var x = 0;
var screenWidth = window.innerWidth;

window.onscroll = function() {
  var box = document.getElementById("main-image");

  setInterval(function() {
    if (x <= screenWidth) {
      x++;
      box.style.left = x + "px";
    } else {
      box.style.display = "none";
    }
  }, 10);
}
.site-header {
  background-image: url("https://images.pexels.com/photos/2159065/pexels-photo-2159065.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200");
  height: 100vh;
  background-repeat: no-repeat;
  background-size: cover;
  justify-content: center;
  position: relative;
}

#main-image {
  position: marker;
  left: 0;
  transition: ease-out;
}
<div class="container-fluid site-header" id="main-image">
  <div class="image-on-text-container bg-secondary">
    <span class="site-brand"></span>
  </div>
</div>

I wrote this script for this, but it’s moving badly. I want it to move slower, and maybe with some effect, but I don’t know how.

3

Answers


  1. change these two blocks:

         #main-image {
            position: marker;
            left: 0;
            transition: all ease-out 3s;
         }
    

    and this:

         window.onscroll = function () {
            var box = document.getElementById("main-image")
            if (x == 0) {
               x = screenWidth
               box.style.left = x + "px"
            }
         }
    
    Login or Signup to reply.
  2. Calculate the y delta instead and animate transition over a timing value of i.e: 0.Ns and translate the x coordinate over that delta value multiplied by 100 to get the percentage value. Don’t forget to add overflow: hidden; to a parent element

    const elBox = document.querySelector(".image-on-text-container");
    
    const moveImage = () => {
      const rect = elBox.getBoundingClientRect();
      const yDelta = -rect.top / rect.height;
      const x = Math.max(0, yDelta); // prevent negative value (move only to left)
      elBox.style.translate = `${x * 100}% 0`;
    };
    
    addEventListener("scroll", moveImage); // Do on scroll
    moveImage(); // and on init
    * { margin: 0; box-sizing: border-box; }
    
    .site-header {
      overflow: hidden; /* Remove scrollbars */
    }
    
    .image-on-text-container {
      position: relative;
      height: 100vh;
      background-image: url("https://images.pexels.com/photos/2159065/pexels-photo-2159065.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200");
      background-repeat: no-repeat;
      background-size: cover;
      transition: 0.2s ease-out;
    }
    <div class="container-fluid site-header" id="main-image">
      <div class="image-on-text-container bg-secondary">
        <span class="site-brand"></span>
      </div>
    </div>
    
    <p style="height: 100vh;">Scroll back up.....</p>
    Login or Signup to reply.
  3. Animating elements through their position values (e.g. left) has its drawbacks and does not render as smoothly as translates do, since it cannot be purely calculated by the gpu. See a more detailed explanation here.

    Here is an example with transform: translatex() set as a global CSS variable.

    const styleRoot = document.querySelector(':root');
    const windowWidth = window.innerWidth;
    const scrollHeight = document.body.scrollHeight;
    let lastScrollTop = 0;
    const factor = 1;
    
    // Sets a global css Variable var(--boxTranslate)
    function setTranslate(xValue) {
     styleRoot.style.setProperty('--boxTranslate', `translateX(-${xValue * factor}px)`);
    }
    
    // Checks if element is on screen
    function isVisible(element) {
      const rect = element.getBoundingClientRect();
      const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
      return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
    }
    
    function onScroll(scrollEvent) {
      const box = document.getElementById('box')
      
      if (!box) {
        return
      } else if (!isVisible(box)) {
        box.remove();
      }
      
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      if (scrollTop > lastScrollTop) {
        // Scrolling down
        setTranslate(scrollTop)
      }
    }
    
    window.onscroll = onScroll;
    body {
      min-height: 5000px;
      overflow-x: hidden;
    }
    
    #box {
      height: 500px;
      width: 500px;
      background-color: teal;
      transition: all 125ms ease-out;
      transform: var(--boxTranslate);
    }
    <div id="box">
      I go left as you scroll and get removed when I'm out of sight
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search