Search code examples
javascriptcssevent-handling

Mouseover event doesn't propagate as expected (Add Button effect)


I wanted to do a simple highlight on a button at the place where you hover over it, following the cursor. If anyone knows a way to do this without js that would be even better (found one crazy post out there), but i tried to do it with a eventhandler for mouseover.

I am moving the nested div when hovering over the button, but on my site it doesn't propagate the event when hovering over the child and in this simple recreation it only works when hovering over the child. Feeling like i am doing something really wrong here but can't see it.

var button = document.querySelector('.button');
var highlightDiv = document.querySelector('.highlight');

button.addEventListener('mouseover', (e) => {
    const x = (e.pageX - button.offsetLeft - 300 / 2) + 15;
    const y = (e.pageY - button.offsetTop - 100 / 2) + 15;
    highlightDiv.style.setProperty('--x', `${x}px`);
    highlightDiv.style.setProperty('--y', `${y}px`);
});
.button {
  border: 1px solid black;
  width: 400px;
  height: 70px;
}

.highlight {
  height: 40px;
  width: 40px;
  background: radial-gradient(#e66465, #9198e5);
  transform: translate(var(--x), var(--y));
}
<button class="button">
  Button Text
  <div class="highlight"></div>  
</button>


Solution

  • Let's use a radial gradient, centered on the mouse position.

    const button = document.querySelector('.button');
    
    button.addEventListener('mousemove', (e) => {
      button.style.setProperty('--x', `${e.offsetX}px`);
      button.style.setProperty('--y', `${e.offsetY}px`);
    });
    .button:hover {
      background-image: radial-gradient(at var(--x) var(--y), #e66465, #9198e5);
      cursor: pointer;
    }
    
    .button {
      border: 1px solid black;
      width: 400px;
      height: 70px;
    }
    <button class="button">
      Button Text
      <div class="highlight"></div>  
    </button>

    Here's a nicer example. AI assisted.

    const button = document.getElementById('radialButton');
    
    button.addEventListener('mousemove', (e) => {
      button.style.setProperty('--x', `${e.offsetX}px`);
      button.style.setProperty('--y', `${e.offsetY}px`);
    });
    #radialButton {
      position: relative;
      padding: 20px 40px;
      font-size: 18px;
      cursor: pointer;
      background-color: #3984ff;
      color: white;
      border: none;
      border-radius: 5px;
      transition: background-image 0.3s;
    }
    
    #radialButton:hover {
      background-image: radial-gradient(
        circle at var(--x, 50%) var(--y, 50%),
        rgba(255, 255, 255, 0.3) 0%,
        rgba(255, 255, 255, 0) 50%
      ),
      linear-gradient(#3984ff, #3984ff);
    }
    <button id="radialButton">Hover me</button>