Search code examples
javascriptcsstexthover

Change Text On Hover With Special Cursor


Please guide me on how to change text on hover, similar to the monopo website. I do not require the background. Only a simple circle effect (like a coloured background) and the text changing would do. Moreover, if possible i want the effect to be active only in a div called "about". enter image description here link to the website : https://monopo.london/


Solution

  • Here's a simple example to get you started.

    The text in the 'lens' is in an element on top of the primary text. It is clipped into a circle at the mouse position on every mouse move. It's background is white so it looks as though it's overwriting the text beneath.

    <style>
      .about {
        position: relative;
        --x: -0;
        --y: -0;
        font-size: 48px;
      }
      
      .overlay {
        position: absolute;
        background: white;
        top: 0;
        left: 0;
        z-index: 1;
        clip-path: circle(1em at var(--x) var(--y));
        color: red;
      }
    </style>
    <div class="about">
      <div class="underneath">This is some text <br>and some more</div>
      <div class="overlay">Different characters<br>and again more</div>
    </div>
    <script>
      const about = document.querySelector('.about');
      about.addEventListener('mousemove', function() {
        const x = event.clientX;
        const y = event.clientY;
        about.style.setProperty('--x', x + 'px');
        about.style.setProperty('--y', y + 'px');
      });
    </script>

    Edit: more context has now been given and the about element (class now renamed to aboutt)is inside other elements.

    We need to get the position relative to .aboutt

    const about = document.querySelector('.aboutt');
    about.addEventListener('mousemove', function() {
      let rect = about.getBoundingClientRect();
      let x = event.clientX - rect.left; //x position within the element.
      let y = event.clientY - rect.top; //y position within the element.
      about.style.setProperty('--x', x + 'px');
      about.style.setProperty('--y', y + 'px');
    });
    <style>
      .aboutt {
        position: relative;
        --x: -0;
        --y: -0;
        font-size: 48px;
      }
      
      .overlay {
        position: absolute;
        background: white;
        top: 0;
        left: 0;
        z-index: 1;
        clip-path: circle(1em at var(--x) var(--y));
        color: red;
      }
    </style>
    <div class="aboutt">
      <div class="underneath">This is some text <br>and some more</div>
      <div class="overlay">Different characters<br>and again more</div>
    </div>

    Also note that in the actual site the background is an image which is mainly black so the white background will need to become background: black.

    And the method will not be perfect against an image rather than a plain color.