Skip to content
Advertisement

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>

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement