How do I make a text move vertically while scrolling [HTML, CSS, JavaScript]

320 Views Asked by At

I wan't to make the h1 text move up vertically while scrolling simultaneously it will be changing font size from 300 to 50. I have got the 2nd part (size changing) of the code working but can't figure out how to make the text move up vertically while scrolling.

const text = document.querySelector('h1');

window.addEventListener('scroll', () => {
    const current = window.scrollY;
    const maxFontSize = 300;
    const minFontSize = 50;
    const fontSize = Math.max(minFontSize, maxFontSize - current);
    text.style.fontSize = `${fontSize}px`;
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: black;
    min-height: 145vh;
}

h1 {
    font-size: 300px;
}

.container {
    color: #18408B;
    text-align: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    min-height: 100vh;
    display: grid;
    place-content: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NBA</title>
    <link rel="icon" sizes="1800x1800" href="Images/logo.png">
    <link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body>
    <div class="container">
        <div class="heading">
            <h1>NBA</h1>
        </div>
    </div>




    <script src="script.js"></script>
</body>

</html>

2

There are 2 best solutions below

2
DEBASISH On BEST ANSWER

    window.onscroll = function() {myFunction()};
    function myFunction() {
      var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
      var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
      var scrolled = (winScroll / height) * 100;
      
      // Change the top position of the h1 text as you scroll
      document.getElementById("myH1").style.top = (50 - scrolled / 2) + "%";
      
      // Change the font size of the h1 text as you scroll
      document.getElementById("myH1").style.fontSize = (300 - scrolled * 2.5) + "px";
    }
    h1 {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
<body onscroll="myFunction()">
  <h1 id="myH1">Hello World</h1>
  <div style="margin:0px auto;width:200px;height:800px;"></div>
</body>

0
Afzal K. On

In your CSS file, create a keyframe animation for the "scroll-text" class. eg:

@keyframes scroll {
    0% {
        transform: translateY(0);
    }
    100% {
        transform: translateY(100px);
    }
}

then add the animation to the "scroll-text" class, with a desired duration and timing function:

.scroll-text {
    animation: scroll 2s ease-in-out infinite;
}

you can also use the scroll-behavior property to make the text scroll smoothly.

.scroll-text {
    scroll-behavior: smooth;
}