Issue encountered while adjusting SVG animation with CSS and JavaScript

I came across an intriguing code on CodePen that I wanted to replicate. However, despite my best efforts, I couldn't get it to work properly. Here is the link to the original code: http://codepen.io/thebabydino/pen/LpqEmJ

When I checked the console, it showed me the following error:

TypeError: rotor is null engine.js:176:1

The code snippet is as follows:

HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>For You</title>
<link href="style.css" rel="stylesheet">
<script type="application/javascript" src="engine.js"></script>
</head>
<body>
<p><a href='http://codepen.io/thebabydino/pen/RWvaZW' target='_blank'>see also the pure CSS (WebKit-only) version</a></p>
<svg viewbox='-2000 -2000 4000 4000'>
<g id='rotor'>
<polygon id='morpher'></polygon>
</g>
</svg>
<h1>click it, you know you want to!</h1>
</body>
</html>

CSS

html { text-align: center; }

body { background: #000; color: #fff; }

svg { width: 65vmin; hight: 65vmin; }

polygon { cursor: pointer; }

h1, p { font: 2em trebuchet ms, verdana, sans-serif; }

p { font-size: 1em; }

a { color: greenyellow; }

JS

// JavaScript Document
Object.getOwnPropertyNames(Math).map(function(p) {
    window[p] = Math[p];
});

var PRECISION = 4, 
    RC_PENTA = 500, 
    A_HEART = PI/4, 
    DURATION = 40, 
    END_SHADES = [[255, 215, 0], [220, 20, 60]], 

    tl = [], shades = [], 
    t = 0, t_incr = 1, rid = null,
    rotor = document.getElementById('rotor'), 
    morpher = document.getElementById('morpher');

var getData = function(prec, rc_penta, a_heart) {
var n_penta = 5, data = { 'prec': prec }, 
        ca_penta = 2*PI/n_penta, 
        ri_penta = rc_penta*cos(.5*ca_penta), 
        hl_penta = rc_penta*sin(.5*ca_penta), 
        ai_penta = (n_penta - 2)*PI/n_penta, 
        ao_penta = PI - ai_penta, 
        ho_star = hl_penta*tan(ao_penta), 
        d = rc_penta + ri_penta + ho_star, 
        diam_heart = d*sin(a_heart);

data.nvx_star = 2*n_penta;
data.ba_star = .5*ca_penta;
data.r_star = [ri_penta + ho_star, rc_penta];

data.nr_heart = n_penta*prec - 1;
data.r_heart = .5*diam_heart;
data.yu_heart = -diam_heart*sin(a_heart);
data.yl_heart = data.yu_heart + d;
data.xo_heart = data.r_heart*cos(a_heart);
data.yo_heart = .5*data.yu_heart;
data.ba_heart = PI/data.nr_heart;
data.aoff_heart = PI - a_heart;

return data;
};
...

If anyone can help me identify where I went wrong, I would greatly appreciate it. Thank you in advance.

Answer №1

Whenever a script tag is discovered, the browser executes it before continuing to parse the rest of the document. This means that when your javascript code runs, the rotor element has not been created yet, which is why it appears as null.

To resolve this issue, move your script tag to the end of the body element so that the code can run successfully.

It's generally recommended to place your scripts at the bottom of the body section (just before the closing </body> tag) in order to enhance rendering speed.

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

"The Ajax BeginForm for a list is only returning the first element of the model, or nothing at

Attempting to trigger an action using an ajax-beginform. This is the model structure being used: public class MyViewModel { public List<SubViewModel> SubViewModels {get;set;} } public class SubViewModel { public string Name {get;set;} ...

Having trouble loading a listbox with JSON data using jQuery

I need help populating a ListBox using jQuery/Json. The code snippet below shows my current approach: jQuery within document.ready: $('#<%=txtSearch.ClientID %>').keyup(function() { if ($('#<%=txtSearch.ClientID %>&apos ...

Slerping with quaternions in Three.js can produce undesirable outcomes when near the poles

Check out this video example: https://drive.google.com/file/d/18Ep4i1JMs7QvW9m-3U4oyQ4sM0CfIFzP/view In the demonstration, I showcase how I determine the world position of a ray hitting a globe under the mouse cursor. By utilizing lookAt() with a THREE.Gr ...

Generating a new DOM element for each AJAX response received

I am working on a project to build an application that fetches data about restaurants and places of interest from the Yelp API and then generates a materialize "card" for each response. Below is the code I have so far. function callback(results, status) ...

Slideshow feature for showcasing images from a dynamic folder

Creating an autoslide gallery is my goal, but I'm not sure where to begin. It needs to be dynamic since the folder content will keep changing over time. Instead of manual input, I want a more automated solution. Do you have any advice or tutorials tha ...

Discover the art of utilizing two distinct binding strings, wherein upon the selection of either, the alternate binding string shall automatically be

Having to use two different bindingstrings is a requirement due to a tool used for creating PDFs. My objective is to have the corresponding bindingstring turn "Off" when a user clicks on either the Yes or No button, and have the clicked button turn to "Yes ...

Is it possible to implement PortalVue in multiple Vue.js single file components?

While working on Vue.js (single file components), I have discovered three methods of passing data around: local state/props, store, and utilizing PortalVue. Through my experiments with PortalVue, I successfully implemented both portal and portal-target wit ...

Tips for positioning a div element in a consistent location and ensuring that .data() values are retained after the page is reloaded

Is there a way to dynamically append resizable and draggable div tags inside another div, while also storing values for each div using .data()? Take a look at the demo below: https://i.sstatic.net/x7IZ8.png I want to position the child divs within the pa ...

How can I apply bold styling to primary nodes in jsTree using CSS?

I am currently utilizing the in conjunction with asp.net mvc. My objective is to apply bold styling to the text using CSS within the main nodes, specifically those with arrows (refer to the image below). https://i.sstatic.net/xg3uF.png Below is the code ...

Having trouble finding the right position, body extending beyond the viewport?

I've encountered a puzzling issue... I attempted to position an element at the far right of the page using CSS 'right: 0px'. However, it appears that my element is actually being placed slightly further right than intended, causing part of i ...

Deciphering the intricate mechanics behind _.bind

This block of code is an excerpt from the Underscore library, specifically showcasing the implementation of the _.bind function. However, I am struggling to comprehend the purpose behind modifying the prototype of an empty function. var customConstruc ...

Which is more advantageous for creating a new block in Bootstrap 4 – using ".row" or ".col-12"? And what is the reasoning behind your choice?

Here is a simple example to demonstrate. <div class="container"> <div class="row"> <form class="col-12 form-group"> // some code </form> <div class="col-12"> // some text for description </d ...

Ways to dynamically display a button on a JQuery table

Deleting rows in a table can be done by clicking on the Remove Button. However, it is important to note that at least one row must always be present. To ensure this, I am checking the length of the table: if($("#dynamicTable1 tr").length==2) { ...

Blur Event Triggered in Primefaces Editor

My current setup involves using JSF Mojarra 2.2.8 with PrimeFaces 5.1, where I utilize a PrimeFaces editor for text input. I am looking to automatically upload the entered text via ajax. However, the editor only supports an onchange event. I'm seekin ...

Ajax divides the data received from a MySQL database

I have been working on an ajax call that looks like this: function myCall() { var request = $.ajax({ url: "ajax.php", type: "GET", dataType: "html" }); request.done(function(data) { $("image").attr(& ...

Guide to customizing the Materialize Datepicker to change styling when clicking on a specific day

I am currently utilizing the Materialize Datepicker to toggle holidays in a list. In my code, when I click on a specific day, the event is either added or removed from the list immediately. However, the style within the datepicker only updates when I selec ...

Want to learn how to create an image magnifier using just one image?

At first, I created an image magnifier that would zoom in when the user hovered over the image. However, now I am looking to switch to a lens zooming method that uses only one image. ...

Set up counters for a variety of Owl Carousel sliders

I am looking to set up multiple owl carousel sliders, where each slider has a counter to track its position. I want the counters to update independently, but I'm running into issues with them not working correctly. Each slider should display a counte ...

Flash notifications are failing to display in the express/nodejs/ejs setup

I've been troubleshooting my flash messages for an hour now, but they just won't seem to work. I'm sure there's something obvious that I'm missing, but no matter what I try, nothing seems to fix it. Here is my Middleware setup: / ...

Guide to positioning an image at the center across 2 columns using Bootstrap

Looking to create a split screen Bootstrap 4 layout with an image in the center overlapping the two columns. Have successfully set up two equal columns but struggling to position the image to overlap. Have experimented with position:absolute and float:lef ...