Make a div smaller when scrolling

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
    aDiv.style.width = (800*100/scrollVal) + "px";
  }

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

Leave a Reply