Home > other >  how to make a horizontal animation that works synchronously with the scroll? (JS)
how to make a horizontal animation that works synchronously with the scroll? (JS)

Time:07-12

Can you please tell me how to make a horizontal animation that works synchronously with the scroll?

I made a sample, but there is a drawback - the event has a start and end point, and I want to make a permanent animation:

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

function animateTx() {
    if (document.documentElement.scrollTop > 50) {
    targetTx.classList.add('active');
  } else {
    targetTx.classList.remove('active');
  }
}

window.onscroll = function() {animateTx()};
section {
  height: 600px;
  border-bottom: solid 1px #000;
  overflow: hidden;
}
h1 {
  display: block;
  font-size: 10rem;
  color: #999;
  white-space: nowrap;
  transition: 0.5s;
}
h1.active {
    margin-left: -50%;
    transition: 0.5s;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <section>
    <h1>TEST TEXT</h1>
  </section>
  <section></section>
</body>
</html>

Thank you in advance!

CodePudding user response:

Use css animations:

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

function animateTx() {
    if (document.documentElement.scrollTop > 50) {
    targetTx.classList.add('slide-anim');
  } else {
    targetTx.classList.remove('slide-anim');
  }
}

window.onscroll = function() {animateTx()};
section {
  height: 600px;
  border-bottom: solid 1px #000;
  overflow: hidden;
}
h1 {
  display: block;
  font-size: 10rem;
  color: #999;
  white-space: nowrap;
}

.slide-anim {
  animation: slide 3s linear infinite;
}

@keyframes slide {
  0% {
    margin-left: 0;
  }
  25% {
    margin-left: -50%;
  }
  50% {
    margin-left: 0%;
  }
  75% {
    margin-left: 50%;
  }
  100% {
    margin-left: 0;
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <section>
    <h1>TEST TEXT</h1>
  </section>
  <section></section>
</body>
</html>

  • Related