Make a div smaller when scrolling

Issue

Hi i tried to make the div smaller wqhen scrolling. however i found some article that the div is small then when scroll it make bigger. i wanted the opposite. when run the image is 100% then when scroll it will be smaller. can someone help me please? i am new to this

This is the code:

https://codesandbox.io/s/sharp-lewin-to1o2b?file=/index.html

Html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
  </head>
  <body>
    <div id="animatedDiv"></div>
  </body>
</html>
<style>
  #animatedDiv {
    background: #dc143c;
    min-height: 9000px;
    min-width: 20%;
    position: absolute;
  }
</style>

<script>
  var aDiv = document.getElementById("animatedDiv");

  function changeWidth() {
    var scrollVal = window.pageYOffset;
    var scrollSlow = scrollVal / 4;

    //Changing CSS Width
    aDiv.style.width = Math.min(Math.max(scrollSlow, 20), 100) + "%";
  }

  window.addEventListener(
    "scroll",
    function () {
      requestAnimationFrame(changeWidth);
    },
    false
  );
</script>

Solution

I did it with my math logic

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
  </head>
  <body>
    <div id="animatedDiv"></div>
  </body>
</html>
<style>
  #animatedDiv {
    background: #dc143c;
    min-height: 9000px;
    width: 100%;
    position: absolute;
  }
</style>

<script>
  var aDiv = document.getElementById("animatedDiv");

  function changeWidth() {
    var scrollVal = window.pageYOffset;

    //Changing CSS Width

/* This lags if you scroll fast.. aDiv.style.width = (100 - (scrollVal*100/800)) + "%"; 
  I just tried it out, so instead use the code down above, 800 to 1500 doesn't matter, I just increased time of animation
*/
//NOTE this line checks if PERCENT <= 10 then sets width to 10%
  ( (100 - (scrollVal*100/1500)) ) <= 10 ? aDiv.style.width = "10%" : aDiv.style.width = (100 - (scrollVal*100/1500)) + "%";
  }

  window.addEventListener(
    "scroll",
    function () {
      requestAnimationFrame(changeWidth);
    },
    false
  );
</script>

Answered By – Sevada 797

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published