0

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 
5
  • why it works only on snippet??? but not on browser :((( Commented Nov 13, 2022 at 7:40
  • Please post the complete code exactly as you have it in the file(s) in vscode, and then it will be easier to diagnose the issue. Commented Nov 13, 2022 at 7:45
  • @JD_dev It doesn't show up? I already post the complete file :( Commented Nov 13, 2022 at 7:48
  • It Works on the browser you just need to review the code in your file. Commented Nov 13, 2022 at 7:50
  • You have only the code in the post in an HTML file without any other code or structure? And is it in the same order that appears in the post (i.e. JS, CSS, HTML). The code runs fine if it's in a properly structured HTML file. Commented Nov 13, 2022 at 7:56

1 Answer 1

3

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank youuu soo muchhhhh. it workssss adding deferrrrr

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.