Harish Karthick
Harish Karthick

Reputation: 720

Undefined Error in Type Script

I am new to Type Script and i am Trying to convert a small piece of javascript code to typescript & getting an error: typeError list[i] is undefined. Here is my Actual js:

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 My Tried fiddle https://jsfiddle.net/hahkarthick/8cwcb970/3/

Upvotes: 0

Views: 71

Answers (2)

Lalit
Lalit

Reputation: 1369

Use i directly instead of list[i].

Also you will have to pass function name instead of false in below code.

i.addEventListener("dragstart", false);

Full 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

Upvotes: 3

Suren Srapyan
Suren Srapyan

Reputation: 68685

When you use for of, your i is the current item, not it's index. So you just need to use i, not list[i].

Your function need to look like this.

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

One more thing, you will get an error because the second parameter of addEventListener must be a function. Pass a function into.

Upvotes: 2

Related Questions