Type Script is throwing an unidentified error being encountered

I am a beginner in Type Script and I'm attempting to convert a small piece of javascript code into typescript, but I keep encountering an error: typeError list[i] is undefined. Here is my original js code:

function handleDragStart(e) {
  this.style.opacity = '0.4';  // this / e.target is the source node.
}

var cols = document.querySelectorAll('#columns .column');
[].forEach.call(cols, function(col) {
  col.addEventListener('dragstart', handleDragStart, false);
});

Here is the fiddle I attempted: https://jsfiddle.net/hahkarthick/8cwcb970/3/

Answer №1

Instead of using list[i], it is recommended to directly use the variable i.

Make sure to pass the function name instead of false in the code snippet below.

i.addEventListener("dragstart", functionName);

Complete code :-

    class col {
  itrate(): any {
    let list: any = document.querySelectorAll("#columns .column");
    let i:any;
    for ( i of list) {
        console.log(i);
      console.log(list[i]);
      i.addEventListener("dragstart", this.dragStart);
    }
  }
  dragStart(event): any{
    console.log(event);
  }
}
let colz: any = new col();
colz.itrate();

Fiddle Link :- working code

Answer №2

Using the for of loop, the current item is stored in the variable i, rather than its index. Therefore, you should simply use i instead of list[i].

Your function should be structured like this:

iterate(): any {
   let list: any = document.querySelectorAll("#columns .column");
   for (let i of list) {
     console.log(i);
     i.addEventListener("dragstart", false);
   }
}

Additionally, make sure to provide a function as the second parameter for the addEventListener method to avoid errors.

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

Deleting the clone <div> while ensuring the main <div> is kept clear of any remaining data

Initially: https://i.sstatic.net/SLG7O.png After adding a new row and then removing it. https://i.sstatic.net/FegjK.png Why is this happening? When I set val(""), the textbox should have no value. What mistake did I make in my code? Please assist. Her ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

What is the best way to utilize JSON data stored in a Jekyll _data folder?

As per the documentation on Jekyll, it is mentioned that you can access YAML, JSON, and CSV files located in the `_data` directory using `{{ site.data.filename }}`. I have a geoJson file named `chapters.json` which consists of point features. While I am a ...

What is the best method for retrieving data from a specific collection in MongoDB?

Within the code snippet below, on the 4th line, 'Messages' is the name of my MongoDB collection that I created in another file. When I attempt to retrieve data from this collection, no errors occur. However, when I specify the name of a differen ...

Can TypeScript accurately perform the _.invert function?

When using lodash, you can utilize the _.invert function to switch an object's keys and values: var object = { 'a': 'x', 'b': 'y', 'c': 'z' }; _.invert(object); // => { 'x': &a ...

Tips for keeping the most recently opened accordion in a group by using the is-open attribute to call a function

I have a dynamically populated accordion that updates every 15 seconds. I need to keep track of the last opened accordion group as the dataList can be very large and parsing it for each update is not feasible. Below is the code snippet from my HTML file: ...

NextJS is throwing an error stating that the element type is invalid. It was expecting either a string for built-in components or a class/function for composite components, but instead received an object

I encountered the following issue: Error - Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but received an object. Here's the code from my \components\LayoutWrapper.js: i ...

Creating a visually stunning image grid akin to the meticulously designed layouts found

Forgive my lack of knowledge, but I'm curious about how to create an image or text grid similar to Tumblr using HTML and CSS. I'm looking to achieve a layout like this: ...

What is the best way to connect users for chatting?

I am currently developing a cutting-edge chat application with a real-time communication server that allows me to send and receive messages seamlessly. The next step in my project involves mapping users for private real-time communication. I'm faced w ...

Adjust a parameter within a MongoDB array entity

I am attempting to update a value within an array of objects. Looking at the MongoDB schema above, my goal is to find an expense with an ID that matches the _id and update the fields with new values from req.body. Specifically, I need to update expensesTyp ...

Filter an array of objects in Javascript based on a key present in another array of objects

Having two arrays, one with all products and one with products a user can access, both sharing a common ID. The goal is to filter the products array to only include those accessible to the user. All available products (products) [{ "productName": "My P ...

What is the best way to narrow down the content cards displayed on the page?

I have recently developed a blog post featuring three distinct categories: digital marketing, tips and advice, and cryptocurrency. My goal is to implement a filtering system for these categories. For instance, I would like users to be able to click on a b ...

JavaScript method for altering the values of variables

Having a small issue with my JavaScript function. Let me tell you what's going on: var intervalId = setInterval(function() { var value = parseInt($('#my_id').text(), 10); if(value > 0) { clearInterval(intervalId); console.log ...

Event callback type narrowing based on the specific event key

While exploring different approaches to create a type-safe event emitter, I came across a pattern where you start by defining your event names and their corresponding types in an interface, as shown below: interface UserEvents { nameChanged: string; ...

Are you experiencing difficulty loading ng-view in AngularJs?

I am new to AngularJs. I am currently using a wamp server and have successfully loaded the HTML page, but unfortunately the view is not being displayed. I have added ng-app to the body as well, but still unable to load the view. <!DOCTYPE html> ...

What is the process for retrieving the array of points from a polygon shape?

My current challenge involves working with a JSON file containing an array of states and a sub-array of corresponding latitude (lat) and longitude (lng) values. After looping through the states and points to build 50 polygons, I now need to center and zoo ...

Using a JSON key as a parameter in a function

Would it be achievable to specify the key of an object as a function parameter? For instance, if I were to develop a filter function that could sort multiple map markers by marker.element.country or marker.element.population? This approach would allow me ...

What is the best way to retrieve data based on conditions in React?

I'm currently learning React and trying to pass props from a parent component (table row) to a child Modal component. Inside the child component, I want to fetch data based on the props provided. I have created a custom hook called useFetch that store ...

Is there a clash with another code causing issues in troubleshooting a straightforward jQuery function?

jQuery(document).ready(function() { jQuery("#bfCaptchaEntry").on("click", function(){ jQuery("#bfCaptchaEntry").css("background-color", "#FFFFFF"); }); jQuery("#bfCaptchaEntry").on("blur", function(){ jQuery("#b ...

Angular 2/4 throws an Error when a Promise is rejected

I implemented an asynchronous validator function as shown below. static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> { return new Promise((resolve, reject) => { setTimeout(() => { if (contr ...