Home > Back-end >  something wrong with onmousemove
something wrong with onmousemove

Time:11-13

I am trying to write script on my button. I don't know what's wrong in my code.but, when I tried to wrote it on codepen it works perfectly as my expected. I wrote it on vscode before but caught an error.

I tried to recreated it in external js, but didn't work either

const btn = document.querySelector('.btn');
      btn.onmousemove = function (e) {
        const x = e.pageX - btn.offsetLeft;
        const y = e.pageY - btn.offsetTop;

        btn.style.setProperty('--x', x   'px');
        btn.style.setProperty('--y', y   'px');
      };
.btn {
  position: relative;
  display: inline-flex;
  padding: 10px 30px;
  background-color: #363636;
  color: #fff;
  text-decoration: none;
  letter-spacing: 2px;
  overflow: hidden;
}

.btn span {
  position: relative;
  z-index: 1;
}

.btn::before {
  content: "";
  position: absolute;
  top: var(--y);
  left: var(--x);
  transform: translate(-50%, -50%);
  width: 0;
  height: 0;
  border-radius: 50%;
  background: #2196f3;
  transition: width 0.6s, height 0.6s;
}

.btn:hover::before {
  width: 300px;
  height: 300px;
}
<a href="#" ><span>Button</span></a>

Uncaught TypeError: Cannot set properties of null (setting 'onmousemove')
        at js.js:2:23

CodePudding user response:

The error is telling you that the element you are trying to change the properties of is null. The reason for this is that your JavaScript code executes before your HTML element loads in.

Wrap your code in a window.onload function and it should work as intended.

window.onload = function(){ 
    // rest of code
};

Alternatively, you can also try adding the "defer" attribute to your script tag in HTML.

<script src="script.js" defer></script>
  • Related