Error: Unable to perform 'getComputedStyle' on the 'Window' object: the first parameter must be of type 'Element'

My goal is to create a rotating effect with a center circle containing 5 inner divs. When the device is rotated on the gamma axis, I want the circle div to rotate in accordance with the gamma degree, while the inner divs rotate in the opposite direction to give the illusion of a Ferris wheel effect. Below is the code I have written for this:

document.addEventListener("DOMContentLoaded",onload); 

function onload(){

    if (window.DeviceOrientationEvent) {
        console.log("DeviceOrientation is supported");
        window.addEventListener('deviceorientation', function(eventData){
            var tiltLR = eventData.gamma;
            deviceOrientationHandler(tiltLR);
        }, false);
    } else {
        console.log("DeviceOrientation NOT supported");
    }
}

var lastTilt = 0;

function deviceOrientationHandler(tiltLR) {
    var circle = document.getElementById('center-circle');
    var str = window.getComputedStyle(circle, null);
    var trans = str.getPropertyValue("-webkit-transform");
    var tr_values = trans.split('(')[1],
        tr_values = tr_values.split(')')[0],
        tr_values = tr_values.split(',');
    circle.style.webkitTransform = "translate("+tr_values[4]+"px, "+tr_values[5]+"px) rotate("+ tiltLR +"deg)"


    var icons = document.getElementsByClassName('icon-circle');
    tiltLR = Math.abs(tiltLR);
    for (var i = 0; i <= icons.length; i++){
        var el = icons[i];
        var st = window.getComputedStyle(el, null);
        var tr = st.getPropertyValue("-webkit-transform");
        var values = tr.split('(')[1],
            values = values.split(')')[0],
            values = values.split(',');
        if (tiltLR > lastTilt) {
            icons[i].style.webkitTransform = "translate("+values[4]+"px, "+values[5]+"px) rotate(-"+ tiltLR +"deg)";
        } else {
            icons[i].style.webkitTransform = "translate("+values[4]+"px, "+values[5]+"px) rotate("+ tiltLR +"deg)";
        }
        console.log("el"+i+": "+tr+" | vals: "+values);
    }

    lastTilt = tiltLR;
}

The issue arises within the for loop - specifically at this line

var st = window.getComputedStyle(el, null);
where I encounter these error messages:
Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
. I attempted to modify the el variable to icons[i].id, but that did not resolve the problem.

Any insights into why this is occurring and how to rectify it would be greatly appreciated.

Answer №1

As @Juhana pointed out in the comments, the reason your last loop is failing is because there is no element

var el = icons[i]; // where i=icons.length

Therefore, you need to adjust your loop like this:

for (var i = 0; i < icons.length; i++){//change <= to <

Once you make this change, everything should work as expected.

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

Having trouble with the post request in Express JS and Vue? Don't worry, we've got you covered

I've been following a tutorial to set up a basic app and everything is working smoothly, except for the post request which seems to be causing me trouble. Tutorial: https://www.youtube.com/watch?v=HkIGAqAP1GY Although the issue is reproducible based ...

Utilizing the "apply" method with JavaScript OOP callbacks for dynamic context management

Encountering an issue while creating a callback in my custom EACH function utilizing Object-Oriented Programming principles. To achieve this, I have developed a JavaScript library that emulates the familiar habits of JQUERY. Experience it in action by ch ...

I'm encountering an issue with VS Code where it is unable to identify ejs tags within my project

I'm running into an issue with Vs code where it's not recognizing ejs output tags when they're inside an html tag, like in the input tag below : <input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form. ...

Hiding labels in an HTML document can be achieved by using CSS

Recently, I've been working on a code that relies on a specific Javascript from Dynamic Drive. This particular script is a form dependency manager which functions by showing or hiding elements based on user selections from the forms displayed. Oddly ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

The `getScript` function in jQuery is not working as expected, even though the path is accurate and the script was successfully downloaded

Recently, I created a website using Mustache.js and incorporated templates loaded via AJAX with jQuery. During the testing phase on my local environment, everything worked perfectly. However, upon uploading the site to my school server, an issue arose whe ...

Select a configuration for binding an array of objects in AngularJS

Plunkr: http://plnkr.co/edit/RgNcSg?p=preview I have a dropdown menu displaying different "locations," which are sourced from an array of objects. Despite setting the object value in my controller, it does not appear selected in the dropdown menu. The HTM ...

What is the solution for - Uncaught TypeError: Cannot access the property 'scrollHeight' of an undefined element?

Could someone kindly assist me in resolving an issue? I recently encountered a problem with a script I have been using on the Chrome console. This script has been working perfectly fine for the past few days. However, today when I ran it, I started receiv ...

tips for getting two ajax json Data from .net

When working with .NET, I am encountering an issue where I need to send two sets of JSON data (test1 and test2) to a .NET controller using JavaScript (ajax). Here is the code snippet for sending the data: .ajax({ type: 'POST', url ...

Leveraging external JSON data in a Jade template with Node.js

Is there a way to successfully pass a Json Object from XMLHttpRequest to my jade file? I am currently experiencing a blank page display and a 500 internal error being sent by the server for the get method. var express = require('express'); var r ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

Setting up JavaScript imports in Next.js may seem tricky at first, but with

Whenever I run the command npx create-next-app, a prompt appears asking me to specify an import alias. This question includes options such as ( * / ** ) that I find confusing. My preference is to use standard ES6 import statements, like this: import Nav f ...

React form submissions result in FormData returning blank data

I am having trouble retrieving the key-value pair object of form data when the form is submitted, using the new FormData() constructor. Unfortunately, it always returns empty data. Despite trying event.persist() to prevent react event pooling, I have not ...

What is the best way to iterate through array elements with AngularJS?

I am looking to showcase array values using the ng-repeat directive, and then call the getimage function with itemid and photoidlist in order to retrieve the image URL. The JSON data that I have is as follows: $scope.productslist = { "json": { "re ...

Tips for effectively combining the map and find functions in Typescript

I am attempting to generate an array of strings with a length greater than zero. let sampleArray2:string[] = ["hello","world","angular","typescript"]; let subArray:string[] = sampleArray2 .map(() => sampleArray2 .find(val => val.length & ...

What is the best way to extract all of the JSON data from Firebase using a web platform?

As a newcomer to Firebase and noSQL databases, I'm encountering difficulties in extracting all the JSON data from the database. Although I've gone through the firecast tutorials and understand how to retrieve specific values by referencing the da ...

Reactjs Promise left hanging in limbo

How can I resolve the pending status of my promise? I have a modal with a form submit in it, where I am trying to retrieve the base64 string of a CSV file. While my code seems to be returning the desired result, it remains stuck in a pending state. c ...

Combining intersecting sets within an array of sets

I am working with an array that contains minimum and maximum values for various sets. Here is an example of what the array looks like: Array ( [0] => Array ( [0] => 1200 [1] => 2400 ) [1] => Arr ...

Automated updating feature with jQuery

Is there a way to use jQuery code to automatically refresh a page after navigating back in the browser history? Here is an example of what I have tried: jQuery(".form_" + form_count).html("<div id='message'></div>") jQuery('#me ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...