skip to Main Content

I was trying to follow a tutorial by Kevin Powell (https://youtu.be/Z-3tPXf9a7M) and I ran into an error right at the end! TT

my query selector is returning null even when I know that the element is in my html page.

Here’s the code:

const pre = document.querySelector("pre");
console.log(pre)

document.addEventListener("mousemove", (e) => {
    rotateElement(e, pre);
})

function rotateElement(event, element) {
    //get mouse position
    const x = event.clientX;
    const y = event.clientY; 
    //console.log(x,y)

    //find middle
    const middleX = window.innerWidth / 2;
    const middleY = window.innerHeight / 2;

    //get offset from middle
    const offsetX = ((x-middleX) / middleX) * 30;
    const offsetY = ((x-middleY) / middleY) * 30;
    //console.log(offsetX,offsetY)

    element.style.setProperty("--rotateX", -1 * offsetY + "deg");
    element.style.setProperty("--rotateY", offsetX + "deg");

}

and the HTML script:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Effect</title>
    <link rel="stylesheet" href="style.css">
    <script src="main.js" type="application/javascript"></script>
</head>
<body>
    <pre class="language-css" tabindex="0"><code class="language-css"><span class="token selector">.awesome-layouts</span> <span class="token punctuation">{</span>
        <span class="token property">display</span><span class="token punctuation">:</span> grid<span class="token punctuation">;</span>
        <span class="token punctuation">}</span></code></pre>

    
</body>
</html>

The exact error is as follows:

Uncaught TypeError: Cannot read properties of null (reading 'style')
    at rotateElement (main.js:23:13)
    at HTMLDocument.<anonymous> (main.js:5:5)

What exactly went wrong and how do I fix it?

2

Answers


  1. add defer to your script tag, your javascript is running before the document is loaded:

        <script defer src="main.js" type="application/javascript"></script>
    
    Login or Signup to reply.
  2. The issue you’re encountering is caused by the fact that the JavaScript code is being executed before the HTML page has finished loading. When the document.querySelector("pre") line is executed, the pre element hasn’t been created yet, so the pre variable is assigned the value null.

    To fix this issue, you can move the script tag that includes your JavaScript code to the end of the body element, just before the closing tag.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search