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?