Changing Color & Sliding Text on Mouse Position

In this tutorial, you will learn how to create a sliding text that changes color depending on mouse position using CSS & JavaScript. When the cursor is positioned at the left or right, the text's color will match the background color of that side. Watch the video below for a detailed tutorial.


HTML

<body>
  <div class="container">
    <div class="line">
      <div class="left">
        <div class="content">
          <span class="text">Lorem</span>
        </div>
      </div><div class="right">
        <div class="content">
          <span class="text">Lorem</span>
        </div>
      </div>
    </div>
    <div class="line">
      <div class="left">
        <div class="content">
          <span class="text">Ipsum</span>
        </div>
      </div><div class="right">
        <div class="content">
          <span class="text">Ipsum</span>
        </div>
      </div>
    </div>
  </div>

  <script>
    window.addEventListener('mousemove', mouseMove);
    window.addEventListener('resize', resize);

    const text = document.querySelectorAll('.text');
    let width = window.innerWidth;

    function mouseMove(e) {
      let position = 350 * (e.pageX / (width/2) - 1);
      
      text.forEach((span) => {
        span.style.transform = 'translate(' + position +'px)'
      })
    }
    
    function resize() {
      width = window.innerWidth;
    }
  </script>
</body>

CSS

body {
  background-image: linear-gradient(90deg, black 50%, white 50%);
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Arial', sans-serif;
}

.line {
  width: 100vw;
}

.left, .right {
  width: 50vw;
  overflow: hidden;
  display: inline-block;
}

.left .content, .right .content {
  width: 100vw;
  text-align: center;
}

.left {
  color: white;
}

.right {
  color: black;
}

.right .content {
  transform: translate(-50vw);
}

.text {
  display: inline-block;
  font-size: 120px;
  line-height: 100px;
  text-transform: uppercase;
  font-weight: bold;
  transition: ease-out .6s;
}