Despite having the <script> placed after the <div>, I continue to encounter a "TypeError: Cannot read properties of null (reading 'style')" error

I am encountering an issue with the code below. The <script> is positioned after the corresponding <div> in the HTML file, both residing within the <body> tags, however, the browser continues to display an error.

<div id="container" class="fancy" draggable="false">
  <span id="l1" class="fly">A</span>
  <span id="l2" class="fly">B</span>
  <span id="l3" class="fly">O</span>
  <span id="l4" class="fly">U</span>
  <span id="l5" class="fly">T</span>
</div>

<script>
  function hoverWord() {
    for (let i = 1; i < 7; i++) {
      let letter = document.getElementById("l" + i.toString());
      let x = Math.floor(Math.random() * 200) - 100;
      let y = Math.floor(Math.random() * 200) - 100;
      let deg = Math.floor(Math.random() * 100) - 50;
      letter.style.translate = `${x}% ${y}% `;
      letter.style.rotate = `${deg}deg`;
    }
    //document.getElementById("container").style.boxShadow = "120px 80px 40px 20px #0ff;";
  }

  function resetWord() {
    for (let i = 1; i < 7; i++) {
      let letter = document.getElementById("l" + i.toString());
      letter.style.translate = `0% 0% `;
      letter.style.rotate = `0deg`;
    }
  }
  let container = document.getElementById("container");
  container.addEventListener("mouseenter", () => {
    hoverWord();
  });
</script>

https://i.sstatic.net/HlVnKiiO.png

I have experimented with placing the <script> inside and outside of the <div>, before and after it, as well as after the </body> tag, yet I still encounter the same error.

Answer №1

Modify the hoverWord function by adjusting the for loop's condition to i < 6. This change is necessary because there are a total of five span elements within the div.container element. Using i < 7 as the condition will lead to issues, specifically when the value of i reaches six. At that point, the function would attempt to locate the id l6, which does not exist and would result in an undefined outcome.

function hoverWord() {
    for (let i = 1; i < 6 /* Changed 7 to 6 */; i++) {
      let letter = document.getElementById("l" + i.toString());
      let x = Math.floor(Math.random() * 200) - 100;
      let y = Math.floor(Math.random() * 200) - 100;
      let deg = Math.floor(Math.random() * 100) - 50;
      letter.style.translate = `${x}% ${y}% `;
      letter.style.rotate = `${deg}deg`;
    }
    //document.getElementById("container").style.boxShadow = "120px 80px 40px 20px #0ff;";
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a unique HTML design with Django Allauth

While there is no shortage of information on the topic, such as this thread and this one, I haven't been able to find a resource that explains it in a way that even a 5-year-old or a designer could grasp :) I only have knowledge of HTML and CSS, and ...

Is it possible to incorporate a PHP if-else statement in the action attribute of an HTML form?

I'm currently developing a form to allow users to create a login username and password. Once the account creation is successful, I want the user to be directed to the actual LOGIN form. To manage this process, I've implemented various checks usi ...

Is it possible to display the bounding box of an object in Threejs?

Originating from Ogre and C++, I have now transitioned to developing with Threejs. When working with Ogre, for debugging purposes, I frequently utilize the following method: Ogre::SceneNode* n = ... n->showBoundingBox(true); This method is simply use ...

Loading an OBJ file from a blob using three.js

I am currently attempting to load an OBJ file from a blob using Three.js. After referring to this resource and successfully loading STL files, I encountered an issue with loading OBJ files. The error message I received is as follows: TypeError: text.indexO ...

"Encountering a glitch with masterpage.cs in Aspx.net and C#

Currently facing a perplexing issue while developing a website using aspx.net and c#. The following code snippet is on my masterpage: protected void Page_Load(object sender, EventArgs e) { if (HttpContext.Current.Request.Url.AbsolutePath == "/ ...

Using Ajax to send data to a PHP script

I am interested in implementing an AJAX call to a PHP script each time a specific button is clicked. The buttons correspond to different directions - right, left, top, and bottom, represented by divs named r, l, t, and b. I have attempted the code below ...

React Modal consistently selects the identical record from a row

I am having an issue with my table that displays multiple jobs from an API call. Each row has a button that should open a modal showing more information about the specific job, but it always opens the modal for the row with the lowest id. Can anyone help m ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

Having trouble keeping the HTML text centered within the div on a responsive layout

Having an issue with keeping text centered in the middle of a div that overlaps an image. It looks fine on desktop but when I try to make it mobile-friendly, things go haywire. I believe the problem lies in using fixed heights for the div, as setting heigh ...

`Are you incorporating Material UI tabs with React Router in your project?`

Looking for help with a project utilizing react/typescript. Here's the react router configuration: const Root = () => ( <> <NavBar/> <Router> <Route path="/" component={Home} /> <Route ...

Guide on how to beautify HTML and generate output files in the identical directory as the current one

Hey there! I'm currently working as a junior front-end developer and have recently delved into using gulp. One of the challenges I face is dealing with HTML files received from senior developers that aren't well-formatted, containing excessive wh ...

Styling using CSS works seamlessly with jsfiddle, but seems to encounter compatibility issues when applied directly in an HTML file. Interestingly, the CSS properties

I'm having trouble with table formatting in Chrome and Firefox. The TR style is not being applied when I load the file into the browser, even though the table and TD styles are working correctly. Interestingly, if I use the code in a fiddle it works ...

Backdrop filter defined in SVG is not showing up in Safari and Chrome browsers

Exploring an interesting example (taken from this source), showcasing the application of the same feTurbulence/feDisplacementMap SVG filter to two HTML elements. One element uses a CSS filter(), while the other employs a CSS backdrop-filter(). On Chrome, b ...

Attempting to establish limits for the movement of a three.js cube

I'm currently working on developing a straightforward app that allows me to move a cube either to the left or right. The movement part has been successfully implemented, and now I am faced with the challenge of ensuring that the cube stays within the ...

Looking for a way to include an input box within a react-select option dropdown menu

Currently, I am facing a situation where I need to include an input box within my dropdown option menu. The challenge is that I cannot utilize the custom tag creator feature of react select to create a new option with the dropdown. Upon going through the ...

Interactive double content slider showcasing dynamic features

I am attempting to customize a W3 slider to be more dynamic. The original slider can be found at this link. My goal is to modify the slider so that only the bottom images are displayed, with only the current image showing at the top. For a visual referenc ...

What is the most efficient method for choosing a class with jQuery?

I'm dealing with a Bootstrap button: customtags/q_extras.py @register.filter(name='topic_check') def is_topic_followed(value, arg): try: topic = Topic.objects.get(id=int(value)) user = User.objects.get(id=int(arg)) ...

Error message: Incorrect XMP data detected within PhotoSphereViewer" and "WebGL issue: INVALID_VALUE error when attempting to load faulty image data

I'm currently utilizing Photo Sphere Viewer to showcase a panoramic image similar to how Facebook does it, but I am encountering some difficulties. Below is the code snippet: <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/em ...

Unraveling based on changing values in es6

Trying to retrieve query parameters from the frontend in my express endpoint. const { filterType1, filterType2 } = req.query However, the issue is that the filterType values are coming from a predefined list of array elements. const list = ['priceF ...

Monitoring the sharing of content on social media networks, rather than tracking individual

After setting up a hidden page on my site and configuring buttons to test pushing data to the dataLayer, I have ensured that my Google Tag Manager (gtm) is functioning properly. I recently tracked a Google +1 button click successfully, confirming that my c ...