javascriptdommousemove

Cannot target button element on mousemove event


My js code is supposed to target the button class and add the cursor-hover-nav on my cursor class

I tried adding a padding on my button and the script worked only when I hovered over the padding and not its main element. Any reasons why it wont work over the main element?

window.addEventListener("mousemove", function(e) {

  if (e.target.className === 'nav-button') {
    cursor.classList.add('cursor-hover-nav');
  } else {
    cursor.classList.remove('cursor-hover-nav');
  }
});
<button onclick="show()" class="nav-button">
  <svg class="plus" viewbox="0 0 100 100" width="40">
    <rect class="line vert" 
      width="80" height="10" x="10" y="45" rx="6">
    </rect>
    <rect class="line horiz" 
     width="10" height="80" x="45" y="10" rx="6">
    </rect>
  </svg>
</button>


Solution

  • The problem is caused by SVG element, it's not clear why, we need a SVG expert here, but since you need it only for graphics, just add pointer-events: none to it. Also I would suggest to check the hover with if (e.target.closest('.nav-button')) since it's more stable when you add child elements to the button.

    But mousemove isn't a good for hover effects since it triggered not precisely. Use mousenter and mouseleave.

    window.addEventListener("mousemove", function(e) {
      Object.assign(cursor.style, {left: e.clientX + 'px', top: e.clientY + 'px'});
      if (e.target.closest('.nav-button')) {
        cursor.classList.add('cursor-hover-nav');
      } else {
        cursor.classList.remove('cursor-hover-nav');
      }
    });
    .as-console-wrapper{
      max-height: calc(100% - 80px) !important;
    }
    .nav-button svg{
      pointer-events: none;
    }
    #cursor{
      width: 8px;
      height: 8px;
      position: absolute;
      margin-top: 16px;
      margin-left: 16px;
      background: yellow;
    }
    #cursor.cursor-hover-nav{
      background: red;
    }
    <button onclick="show()" class="nav-button">
      <svg class="plus" viewbox="0 0 100 100" width="40">
        <rect class="line vert" 
          width="80" height="10" x="10" y="45" rx="6">
        </rect>
        <rect class="line horiz" 
         width="10" height="80" x="45" y="10" rx="6">
        </rect>
      </svg>
      <span>TEXT</span>
    </button>
    <div id="cursor"></div>