Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

something wrong with onmousemove

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="#" class="btn"><span>Button</span></a>
Uncaught TypeError: Cannot set properties of null (setting 'onmousemove')
        at js.js:2:23

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading