Search code examples
javascripthtmlcsscursor

Custom Cursor scrolls away unless mouse is moved HTML CSS JS


I am working on a custom cursor design for my website. I found a design I liked and tweaked it to my liking. The only problem is, when I scroll, the design scroll away too. It returns when I move the mouse.

const cursor = document.querySelector('.cursor')
document.addEventListener('mousemove', (e) => {
  cursor.setAttribute("style", "top: " + (e.pageY - 60) + "px; left: " + (e.pageX - 60) + "px;")
})

document.addEventListener("click", (e) => {
  console.log(e.target)
  cursor.classList.add('click')

  setTimeout(() => {
    cursor.classList.remove('click')
  }, 500)
})
@import url("https://fonts.googleapis.com/css?family=Montserrat:400,400i,700");
body {
  font-family: Montserrat, sans-serif;
  font-size: 30px;
  background: #000;
  color: #fff;
  cursor: none;
  position: relative;
  min-height: 100vh;
  padding: 0px;
  margin: 0px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

div {
  display: inline-block;
  padding: 20px;
}

.cursor {
  pointer-events: none;
  position: absolute;
  width: 80px;
  height: 80px;
  background: #fff;
  border-radius: 50%;
  mix-blend-mode: exclusion;
  background: radial-gradient(circle, #000 0%, #000 3.99%, #fff 4%, #fff 100%);
}

.cursor.click {
  animation: click .3s ease-in-out;
}

@keyframes click {
  0% {
    transform: scale(1);
  }
  5% {
    transform: scale(1.3);
  }
  100% {
    transform: scale(1);
  }
}
<div class="cursor">
</div>
<h1>Hello world</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mi nisi, congue at mattis in, fermentum at purus. In venenatis diam eget facilisis pharetra. Nam eget metus gravida nibh consectetur auctor. Nunc dignissim eros nunc, at tempus dui tincidunt quis. 

Mauris augue dui, pretium vel nunc ac, lacinia condimentum est. Maecenas mattis ligula non mi rutrum sodales. Aenean porta augue eget ex convallis, eget pulvinar felis accumsan. Suspendisse lorem nunc, dignissim at sapien eget, condimentum varius enim. 

Duis bibendum sed justo non laoreet. Ut egestas nisi vel interdum viverra. Ut consectetur ex sed sem pretium, convallis egestas tellus elementum. Maecenas libero felis, efficitur nec dolor et, ultrices dignissim magna.</p>
<br>

I have tried changing pageX and pageY to clientX and clientY but all it did was make the cursor irrecoverable if scrolled too far.


Solution

  • In your css change position: absolute to position: fixed for .cursor

    This will ensure that cursor is relative to the viewport, not the nearest relative positioned ancestor (scrolling doesn't affect viewport but may affect the HTML element, thus the cursor (with position: fixed) should stay in place while scrolling)

    More details here - w3schools link

    And also you need to change pageY and pageX to clientX and clientY in your JS (as client isn't affected by scrolling and page does)