I am writing a simple chrome extension that lists all open tabs, I have this code on it
function changeTab(tabID){ chrome.tabs.update(tabID,{active:false}) } chrome.windows.getCurrent({populate: true},function (window){ list = document.getElementById('open-tabs'); for (var i = 0; i < window.tabs.length; i++) { var li = document.createElement('li'); var element = document.createElement('a'); element.setAttribute('href','#'); element.innerHTML = window.tabs[i].title; element.addEventListener("click",function(){ changeTab(window.tabs[i].id); },false); li.appendChild(element); list.appendChild(li); } });
It displays open tabs, but doesn't seem to add an onClick event, when I checked the chrome console, I get this

Why is the event not being added correctly?
- edit-- Adding html if it helps
<!doctype html> <html> <head> <title>Count Me</title> <link rel="stylesheet" href="popup.css" type="text/css"> <script src="popup.js"></script> </head> <body> <div id="main"> <ul id="open-tabs"></ul> </div> </body> </html>
Edit2
I tried using the sugestion specified in the answer using .bind(this,i) but still does not work, I added console.log() to see what happens and it seems like it is not included in addEventListener . log calls:
function changeTab(tabID){ chrome.tabs.update(tabID,{active:false}) } chrome.windows.getCurrent({populate: true},function (window){ list = document.getElementById('open-tabs'); for (var i = 0; i < window.tabs.length; i++) { var li = document.createElement('li'); var element = document.createElement('a'); element.setAttribute('href','#'); element.innerHTML = window.tabs[i].title; console.log('before'); console.log(window.tabs[i].id); element.addEventListener("click",function(iVal){ console.log('inside'); changeTab(window.tabs[iVal].id); }.bind(this,i),false); console.log('after'); console.log(window.tabs[i].id); li.appendChild(element); list.appendChild(li); } });
As you can see, I have before and after console.log() as well as inside addEventListener , and it does not seem to call anything inside addEventListener , as you can see here:

It calls console.log inside addEventListener , but still not working
