0

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/

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ya i Tried That also and Getting Error: Argument 2 of EventTarget.addEventListener is not an object.
Now Getting Reference Error: i is not defined
@HarishKarthick Check again actually it is due to line i.addEventListener("dragstart", false); added above the code.
@HarishKarthick I have added js fiddle link also.
2

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.

4 Comments

Thanks For You Help and Can you suggest me how to archive that @SurenSrapyan
@SurenSrapyan rejecting an edit with a working fiddle was is a little weird though, but whatever.
OP is working with dragstart, not just showing alert
@SurenSrapyan He does not in his fiddle. But I guess you have not had a look at it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.